home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Amiga Format CD 38
/
Amiga Format CD38 (1999-03-15)(Future Publishing)(GB)(Track 1 of 3)[!][issue 1999-04].iso
/
-in_the_mag-
/
reader_requests
/
dice_v3.15
/
doc
/
dice_libraries.doc
< prev
next >
Wrap
Text File
|
1999-01-26
|
202KB
|
7,659 lines
dice/AslBase,DiceCacheBase,DiskfontBase,DOSBase,FifoBase,GadToolsBase,IconBase,IntuitionBase,LayersBase,MathBase,MathIeeeDoubBasBase,MathIeeeDoubTransBase,MathIeeeSingBasBase,MathIeeeSingTransBase,MathTransBase,RexxSysBase,SysBase,TimerBase,TranslatorB
se,UtilityBase
FUNCTION
DICE will automatically open libraries for you (DICE)
DESCRIPTION
With DICE you need not worry about opening or closing Amiga
libraries. You don't have to deal with the mess and hassle of
checking error returns from each open. If a function call to a
library is used, the library base variable will be referenced. If
you did not explicitly define the variable, DICE will insert it,
along with code to open and close the library.
For example, if the _IntuitionBase base variable is referenced (say,
with extern) but not declared then _IntuitionBase will be
automatically declared in auto.lib. Additionally, auto.lib adds
routines to the autoinit and autoexit sequences that automatically
open "intuition.library" before _main and close it after _exit. If
the auto-open fails the program will be aborted before _main is ever
called. The autoexit routine that closes the library first checks to
see if the base variable is NULL and skips trying to close the
library if so.
EXAMPLE
/*
** Example program which just calls an
** intuition.library function without
** bothering to open the library.
*/
main()
{
DisplayBeep( 0 );
}
dice/abort dice/abort
FUNCTION
abort a program with an error (ANSI)
SYNTAX
#include <stdlib.h>
void abort(void);
DESCRIPTION
abort aborts a program with a non-zero exit code. The default abort
routine in c.lib does the equivalent of an exit(20);. Programmers may
overide the default abort routine with thier own.
RESULTS
abort never returns
SEE ALSO
assert
EXAMPLE
#include <stdio.h>
#include <stdlib.h>
main(int ac, char**av)
{
if (ac == 1) {
puts("Hey, I expected a parameter!");
abort();
}
puts("Thanks!");
return(0);
}
dice/abs,labs dice/abs,labs
FUNCTION
take absolute value (ANSI)
SYNTAX
#include <stdio.h>
#include <stdlib.h>
int r = [l]abs(n);
int n;
DESCRIPTION
abs takes the absolute value of an int; labs takes the absolute value
of a long. Both return the absolute value of the specified integer.
For example, r = n if n >= 0, r = -n (positive) if n < 0. Normally
one would not use this call due to overhead, but it exists for
compatibility.
## WARNING: The absolute value of 0x80000000 cannot be taken.
## 0x80000000 will be returned.
|| NOTE: UNDER DICE, sizeof(int) == sizeof(long) and these two
|| functions are thus identical.
INPUTS
int n; integer
RESULTS
int r; absolute value of integer
EXAMPLE
#include<stdio.h>
#include <stdlib.h>
main()
{
int n = -53;
printf("The absolute value of %d is %d\n", n, abs(n));
sleep(1);
printf("But its faster if you write a macro:\n");
#define abs(x) (((x) < 0) ? -(x) : (x))
sleep(1);
printf("The absolute value of %d is %d\n", n, abs(n));
return(0);
}
dice/access dice/access
FUNCTION
determine whether file is accessable (UNIX)
SYNTAX
#include <stdio.h>
int r = access(filename, mode);
const char *filename;
int mode;
DESCRIPTION
access returns 0 upon success, -1 if access with the requested modes
was impossible. The filename serves as a pointer to the string of
the filename we wish to check, and the modes are what we expect the
file to be able to do. The modes may be one or more of the following
OR'd together.
0 check for existance of file only
1 check execute permission for file
2 check write permission for file
4 check read permission for file
INPUTS
char *filename; file to check
int mode; modes as specified above
RESULTS
int r; 0 if modes available, -1 if not
SEE ALSO
open, fopen
EXAMPLE
#include <stdio.h>
main(int ac, char **av)
{
char *name;
if (ac == 1)
{
puts("Expected a file name argument");
exit(1);
}
name = av[1];
if (access(name, 0) == 0) {
puts("It exists");
if (access(name, 1) == 0)
puts("It is executable");
if (access(name, 2) == 0)
puts("I can write to it!");
if (access(name, 4) == 0)
puts("I can even read from it!");
}
else
puts("Hmmm, that file does not exist");
}
dice/acos dice/acos
FUNCTION
take arc cosine (ANSI)
LIBRARY
m.lib
SYNTAX
#include <math.h>
double a = acos(b);
double b;
DESCRIPTION
acos returns the arc cosine of a double quantity.
INPUTS
double b; double floating point value
RESULTS
double a; result double floating point value
SEE ALSO
asin, atan, cos, exp, fabs, log, log10, pow, sin, sqrt, tan, facos,
fasin
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = acos(0.25);
printf("acos 0.25 = %lf\n", a); /* 1.318 */
}
{ /* less accuracy */
float a = facos(0.25);
printf("acos 0.25 = %lf\n", (double)a);
}
return(0);
}
dice/alloca dice/alloca
FUNCTION
allocate memory from the stack (UNIX)
SYNTAX
#include <stdlib.h>
void *ptr = alloca(long bytes);
DESCRIPTION
alloca comes from the UNIX world. It allocates memory off the stack
for use within a procedure. The allocated memory is automatically
freed when the subroutine returns.
:: Beginner's Note: Do not use alloca if you can help it; alloca is
:: not easily portable across machines.
|| NOTE: When a low stack condition arises, alloca will abort by
|| printing an error message and calling abort; alloca does not
|| currently try to allocate dynamic memory when it runs out of
|| stack. Some implementations of alloca use alloca(0) to free
|| allocated stack. This feature is not currently implemented in
|| DICE's alloca call.
SEE ALSO
setjmp, longjmp
EXAMPLE
#include <alloca.h>
#include <stdio.h>
main(int ac, char*av[])
{
char *ptr;
if (ac == 1) {
puts("I need test string");
exit(1);
}
ptr = alloca(strlen(av[1]) + 8);
sprintf(ptr, "FOO.%s", av[1]);
puts(ptr);
return(0);
}
dice/asctime dice/asctime
FUNCTION
convert broken down time into standard text (ANSI)
SYNTAX
#include <time.h>
char *str = asctime(ts);
const struct tm *ts;
DESCRIPTION
asctime converts a broken down time in the tm structure to an ASCII
string and returns a pointer to that string. The time string format
is:
on Dec 8 01:53:33 1987\n\0
where \n stands for a newline character and \0 is a terminating NULL.
The string is stored in a static buffer shared by both asctime and
ctime and so will be overwritten whenever either function is called.
INPUTS
struct tm *ts; pointer to a broken down time structure
RESULTS
char *str; pointer to static string
SEE ALSO
time, localtime, asctime, strftime, ctime, clock
EXAMPLE
#include <stdio.h>
#include <time.h>
main()
{
time_t t = time(NULL);
fputs(asctime(localtime(&t)), stdout);
return(0);
}
dice/assert dice/assert
FUNCTION
assert that an expression is true, else abort (ANSI)
SYNTAX
#include <assert.h>
assert(condition); /* MACRO */
DESCRIPTION
assert checks the condition and if not true prints an error message
indicating the source filename and line number that the assertion
failed at, and then aborts. The DICE version of assert generates a
single static string in assert.h for each module containing the file
name. Multiple usages of assert refer to the same physical filename
string.
INPUTS
expression; an expression which the macro negates.
SEE ALSO
abort
EXAMPLE
#include <assert.h>
main(int ac, char **av)
{
assert(ac > 1); /* expect at least one argument! */
return(0);
}
dice/asin dice/asin
FUNCTION
take the arc sine of a double quantity (ANSI)
LIBRARY
m.lib
SYNTAX
#include <math.h>
double a = asin(b);
double b;
DESCRIPTION
asin takes the arc sine of a floating point quantity.
INPUTS
double b; double floating point value
RESULTS
double a; result double floating point value
SEE ALSO
acos, cos, exp, fabs, log, log10, pow, sin, sqrt, tan facos, fasin
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = asin(0.25);
printf("asin 0.25 = %lf\n", a); /* 0.2527 */
}
{ /* less accuracy */
float a = fasin(0.25);
printf("asin 0.25 = %lf\n", (double)a);
}
return(0);
}
dice/atan dice/atan
FUNCTION
take arc tan of a double quantity (ANSI)
LIBRARY
m.lib
SYNTAX
#include <math.h>
double a = atan(b);
double b;
DESCRIPTION
atan takes the arc tangent of a floating point quantity.
INPUTS
double b; double floating point value
RESULTS
double a; result double floating point value
SEE ALSO
acos, asin, cos, exp, fabs, log, log10, pow, sin, sqrt, tan facos,
fasin
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = atan(0.25);
printf("atan 0.25 = %lf\n", a); /* 0.245 */
}
{ /* less accuracy */
float a = fatan(0.25);
printf("atan 0.25 = %lf\n", (double)a);
}
return(0);
}
dice/atexit dice/atexit
FUNCTION
specify routine that is automatically called on exit (ANSI)
SYNTAX
#include <stdio.h>
#include <stdlib.h>
int error = atexit(funcptr);
void (*fptr)(void);
DESCRIPTION
The atexit routine adds a function to the list of functions called
when the program exits. The atexit routine is called before stdio
and file descriptors are closed down. This exit function is called
whenever the program exits, even if main returns normally. atexit
will return 0 on success, -1 on failure. Some systems limit the
number of atexit functions one can add (DICE does not) so if you add
more than one you should check the return value.
INPUTS
void (*fptr)(void);
routine to add to exit call list, takes no
arguments and returns nothing.
RESULTS
int error; 0 on success, -1 on failure.
SEE ALSO
onbreak
EXAMPLE
/*
* Atexit is useful to free up resources that would
* otherwise not be freed up by DICE. For example, any
* thing AllocMem'd. The atexit function is called on
* any exit ... return from main, call to exit, or ^C.
*
* Normally your atexit routine cannot make assumptions
* as to what has been allocated and what has not since
* exit can be called from anywhere in the program.
*/
#include <stdio.h>
#include <stdlib.h>
extern void *AllocMem();
void *MemPtr; long MemLen;
void myexit(void)
{
if (MemPtr) /* only if it is allocated */
FreeMem(MemPtr, MemLen);
MemPtr = NULL;
}
/* Now we can take a ^C anywhere... before we allocate,
* after, or even after we free (note I am careful to set
* MemPtr back to NULL!)
*/
main()
{
short i;
atexit(myexit);
for (i = 0; i < 50; ++i)
printf("Before %d\t(%ld)\n", i, AvailMem(0) );
MemLen = 32;
MemPtr = AllocMem(MemLen, 0);
if (! MemPtr) {
exit(20);
}
for (i = 0; i < 50; ++i)
printf("During %d\t(%ld)\n", i, AvailMem(0) );
FreeMem(MemPtr, MemLen);
MemPtr = NULL; /* Mark as freed */
for (i = 0; i < 50; ++i)
printf("After %d\t(%ld)\n", i, AvailMem(0) );
return(0);
}
dice/atof dice/atof
FUNCTION
convert string into double floating point value (ANSI)
SYNTAX
#include <stdio.h>
#include <stdlib.h>
double d = atof(str);
const char *str;
DESCRIPTION
atof converts a string into a double floating point value; it is
equivalent to calling strtod(str, NULL). Please refer to strtod for
more information.
INPUTS
char *str; string, like "1.234E-4";
RESULTS
double d; double fp representation of string
SEE ALSO
strtod
dice/atoi,atol dice/atoi,atol
FUNCTION
convert string into integer (ANSI)
SYNTAX
#include <stdio.h>
#include <stdlib.h>
int x =atoi(str);
long y = atol(str);
const char *str;
DESCRIPTION
atoi and atol convert a string of decimal integers into an integer.
It skips initial white space, processes an optional negative sign
('-'), processes digits '0' - '9', and returns the integer. atoi and
atol have been superseded by the strtol function which can handle
numbers of any base.
|| NOTE: Under DICE, sizeof(int) == sizeof(long), and thus atoi and
|| atol are exactly the same.
INPUTS
char *str; string to convert to int
RESULTS
int x; integer result long y; integer result
SEE ALSO
strtol
EXAMPLE
#include <stdio.h>
#include <stdlib.h>
main()
{
int i = atoi(" \t\t -123");
printf("i = %d (-123?)\n", i);
return(0);
}
dice/bcmp dice/bcmp
FUNCTION
compare two memory buffers (UNIX)
SYNTAX
#include <string.h>
int r = bcmp(s1, s2, bytes)
void *s1;
void *s2;
size_t bytes;
DESCRIPTION
bcmp compares two memory buffers. A byte by byte (unsigned)
comparison is done. When a comparison fails and the byte in s1 is
less than the byte in s2 then -1 is returned. If the byte in s1 is
greater than the byte in s2 then 1 is returned. If the count is
exhausted and all comparisons succeed then 0 is returned indicating
the two buffers are the same.
INPUTS
void *s1; pointer to first buffer
void *s2; pointer to second buffer
size_t bytes; size of each buffer
RESULTS
int r; -1 if buf s1 < buf s2, 0 if buf s1 == buf s2, 1
if buf s1 > buf s2.
SEE ALSO
cmpmem, memcmp, strcmp
EXAMPLE
#include <stdlib.h>
#include <assert.h>
main()
{
unsigned char buf1[] = {5, 12, 13};
unsigned char buf2[] = {5, 12, 13};
int r;
r = bcmp(buf1, buf2, 3);
assert(r == 0);
buf1[2] = 12;
r = bcmp(buf1, buf2, 3);
assert(r < 0);
buf1[2] = 200;
r = bcmp(buf1, buf2, 3);
assert(r > 0);
return(0);
}
dice/c.o dice/c.o
FUNCTION
DICE startup module for all C programs
SYNTAX
The module dlib:c.o is normally specified first in a link line, or
automatically by dcc.
DESCRIPTION
C programs require a bit of code (called "glue") in order to start
execution. This code saves machine registers, sets up global
storage, parses arguments, open libraries and, after the program
terminates, communicates results back to the host Operating System.
For use with the Amiga, DICE includes a suitable startup module
called c.o. This module is automatically include by dcc, and need
not concern most programmers.
The startup module performs the following tasks:
1) Save non-scratch registers.
2) If resident, allocate space for both DATA (Initialized globals) &
BSS (Uninitialized globals - set to zero). Copy initialized data
into the allocated space. Clear the BSS portion of the data space.
If the BSS has already been allocated by the load module but not
cleared, clear the BSS portion of the data space.
3) Clear the ^C (Control C) signal
4) Setup _SysBase, the pointer to the Amiga's master library, Exec.
5) Call all AUTOINIT subroutines (this usually results in at least
the dos.library being opened).
6) Call _main (usually the c.lib version, but you may override it).
7) Fall through to _exit(0). Note that while c.a falls through to
_exit after calling _main, _main itself calls main with:
exit(main(args...)); Thus, main() is always expected to return a
valid value (i.e. not void).
C.O. also handles the low-level _exit (__exit:) in the following
sequence:
1) Call all AUTOEXEC subroutines (this normally closes the DOS
library and other automatically opened libraries such as floating
point).
2) Free all memory allocated by the task, including the small data
segment & BSS space. Note that all variables we use hereafter
have already been placed in registers since the dataspace is no
longer valid.
3) If started from workbench, reply to the workbench mesage, _WBMsg.
4) Restore original registers and rts (exit back to the Operating
System).
c.o also exists in c.lib, however that version is not normally used.
|| NOTE: Normally the programmer does not overide the startup object
|| file (c.o).
However, in some cases a programmer will want to overide _main, as
in:
_main(len, arg) int len; char *arg; {... }
The _main entry point is passed the length and arg pointer unmodified
from the OS. When you overide _main you cannot call any stdio (fopen,
fclose, puts, printf, etc...), any low level IO (open, close, read,
write, etc...), or any C memory allocation routine (malloc, etc...).
Normally _main will be overridden if the programer wishes to save
space, and makes only Amiga system calls (such as Open, Close, Read,
Write, FindTask, etc.). Overriding the C.LIB generally makes
executables much smaller because no extraneous stdio or low level IO
routines are brought in from c.lib. Normally you exit out of _main by
calling _exit(code) (note the underscore).
dice/calloc dice/calloc
FUNCTION
allocate memory and clear (ANSI)
SYNTAX
#include <stdlib.h>
void *ptr = calloc(objsize, numobjs)
size_t objsize;
size_t numobjs;
DESCRIPTION
Numobjs objects each objsize in size are allocated contiguously and a
pointer to the first object is returned. The memory is cleared to 0.
Effectively this is equivalent to malloc(objsize * numobjs), and then
setmem(ptr, objsize * numobjs, 0) . calloc returns NULL if the memory
cannot be allocated.
INPUTS
size_t objsize; size of each object
size_t numobjs; number of objects to allocate
RESULTS
void *ptr; pointer to first object
SEE ALSO
malloc, strdup
EXAMPLE
/*
* allocate 16 objects and fill with junk
*/
#include <stdlib.h>
#include <assert.h>
typedef struct
{
long a, b, c;
}
Junk;
main()
{
Junk *jp;
jp = calloc(sizeof(Junk), 16);
assert(jp);
{
Junk *tj = jp;
short i;
for (i = 0; i < 16; ++i, ++tj)
{
tj->a = 1;
tj->b = 2;
tj->c = 3;
}
}
free(jp);
return(0);
}
dice/chdir dice/chdir
FUNCTION
change current directory (UNIX)
SYNTAX
#include <stdio.h>
int r = chdir(path);
const char *path;
DESCRIPTION
chdir changes the current directory to the specified path, returning
0 on success and -1 on failure.
|| NOTE: When a program exits, the original directory will be
|| restored.
INPUTS
char *path; path to chdir into
RESULTS
int r; return value, 0 if ok, -1 if error
SEE ALSO
getcwd
EXAMPLE
#include <stdio.h>
char buf[512];
main(int ac, char **av)
{
getcwd(buf, sizeof(buf));
if (chdir("RAM:")) {
puts("Couldn't chdir into RAM:");
exit(1);
}
FILE *fp;
if (fp = fopen("yy", "w")) {
fputs("Fight for vegtable rights!\n", fp);
fclose(fp);
puts("created file yy in RAM:");
}
if (chdir(buf)) {
printf("Unable to chdir back into %s\n", buf);
}
return(0);
}
dice/chkabort dice/chkabort
FUNCTION
Check for ^C and take the appropriate action (AmigaDOS)
SYNTAX
(void) chkabort(void);
DESCRIPTION
chkabort checks for a ^C and takes the appropriate action. If the
appropriate action is to exit then this routine does not return.
Stdio and other routines will call chkabort at various points. The
action taken by ^C may be set by the signal or onbreak calls.
SEE ALSO
onbreak, atexit, signal
EXAMPLE
/*
* wait for somebody to hit ^C (note that this is very
* wasteful of CPU and thus isn't a real good example).
*/
main()
{
int i;
for (i = 0; i < 10000000; ++i)
chkabort();
return(0);
}
dice/clearerr dice/clearerr
FUNCTION
Clear error associated with a file pointer (ANSI)
SYNTAX
#include <stdio.h>
void clearerr(fp);
(MACRO) FILE *fp;
DESCRIPTION
The clearerr macro clears both the EOF flag and the ERROR flag
associated with a file pointer. When an ERROR occurs on a file
pointer, addition fread, fwrite, etc. calls will not work until the
ERROR indicator is cleared.
|| NOTE: Refer to the file_pointer manual page for general
|| information.
INPUTS
FILE *fp; file pointer to clear the error on.
RESULTS
none; the error and EOF indicators are cleared
SEE ALSO
feof, ferror, rewind, fseek
dice/clock dice/clock
FUNCTION
return system clock value (ANSI)
SYNTAX
#include <time.h>
clock_t clk = clock(void);
DESCRIPTION
clock returns the system clock in ticks. To obtain seconds from
ticks divide the returned value by CLK_TCK in <time.h>.
INPUTS
none
RESULTS
clock_t clk; system clock time value
SEE ALSO
time, localtime, asctime, strftime, ctime, clock
EXAMPLE
#include <stdio.h>
#include <time.h>
main()
{
clock_t clk = clock();
long i;
clk = clk + CLK_TCK;
for (i = 0; clk - clock() > 0; ++i)
;
printf("The FOR loop calling clock() took\
%d loops in one second\n", i);
return(0);
}
dice/close dice/close
FUNCTION
close a file descriptor (UNIX)
SYNTAX
#include <fcntl.h>
int r = close(fd);
int fd;
DESCRIPTION
close closes a file descriptor. If an error occurs or the descriptor
is invalid, a non-zero return code will result and errno will be set
to the appropriate error condition.
|| NOTE: Refer to the file_descriptor manual page for general
|| information. Unlike file pointers and file handles, the file
|| descriptor is checked for validity and if illegal, an error will
|| be returned.
INPUTS
int fd; file descriptor to close, the file descriptor
becomes invalid after this call
RESULTS
int r; return value, 0 == ok, non-zero == error
SEE ALSO
creat, fcntl, fdtofh, ioctl, isatty, lseek, mkdir, open, read, rmdir,
unlink, write
See open for an example
dice/cmpmem dice/cmpmem
FUNCTION
compare two memory buffers (UNIX)
SYNTAX
#include <string.h>
int r = cmpmem(s1, s2, bytes)
void *s1;
void *s2;
size_t bytes;
DESCRIPTION
Like bcmp, this function compares two memory buffers. A byte by byte
(unsigned) comparison is done. When a comparison fails and the byte
in s1 is less than the byte in s2 then -1 is returned. If the byte in
s1 is greater than the byte in s2 then 1 is returned. If the count is
exhausted and all comparisons succeed then 0 is returned indicating
the two buffers are the same.
INPUTS
void *s1; pointer to first buffer
void *s2; pointer to second buffer
size_t bytes; size of each buffer
RESULTS
int r; -1 if buf s1 < buf s2, 0 if buf s1 == buf s2, 1
if buf s1 > buf s2.
SEE ALSO
bcmp, memcmp
EXAMPLE
#include <stdlib.h>
#include <assert.h>
main()
{
unsigned char buf1[] = {3, 5, 7, 11, 13};
unsigned char buf2[] = {3, 5, 7, 11, 13};
int r;
r = cmpmem(buf1, buf2, 5);
assert(r == 0);
buf1[2] = 2;
r = cmpmem(buf1, buf2, 5);
assert(r < 0);
buf1[2] = 200;
r = cmpmem(buf1, buf2, 5);
assert(r > 0);
return(0);
}
dice/cos,fcos dice/cos,fcos
FUNCTION
cos: return cosine of a double (ANSI)
fcos: return cosine of a float (ANSI)
LIBRARY
m.lib
SYNTAX
#include <math.h>
double a = cos(b);
double c;
float c = fcos(d);
double d;
DESCRIPTION
cos returns the cosine of a type double quantity. fcos is the same,
except expexts a type float. These functions use radian measure.
INPUTS
double b; double floating point value
RESULTS
double a; result double floating point value
SEE ALSO
acos, asin, atan, exp, fabs, log, log10, pow, sin, sqrt, tan facos,
fasin, fcos
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = cos(0.25);
printf("cos 0.25 = %lf\n", a); /* 0.9689 */
}
{ /* less accuracy */
float a = fcos(0.25);
printf("cos 0.25 = %lf\n", (double)a);
}
return(0);
}
dice/creat dice/creat
FUNCTION
create a file (UNIX)
SYNTAX
#include <fnctl.h>
int fd = creat(file);
char *file;
DESCRIPTION
creat creates a new file and returns a file descriptor for it. This
call is equivalent to open(file,O_CREAT|O_TRUNC|O_RDWR); this is an
obsolete function and should not be used.
dice/ctime dice/ctime
FUNCTION
convert time into standard text (ANSI)
SYNTAX
#include <time.h>
char *str = ctime(&t); time_t t;
DESCRIPTION
ctime converts a time pointer into ASCII text using the following
format:
Sun Dec 8 01:53:33 1987\n\0
where \n stands for a newline character and \0 is terminating nul.
The string is stored in a static buffer shared by both asctime and
ctime and so will be overwritten whenever either function is called.
INPUTS
time_t *t; pointer to a time_t value
RESULTS
char *str; pointer to static string
SEE ALSO
time, localtime, asctime, strftime, ctime, clock
EXAMPLE
#include <stdio.h>
#include <time.h>
main()
{
time_t t = time(NULL);
fputs(ctime(&t), stdout);
return(0);
}
dice/dir dice/dir
FUNCTION
disk directory scanning (UNIX)
SYNTAX
#include <sys/dir.h>
DIR *dirhan = opendir(path);
struct direct *entry = readdir(dirhan);
(void) rewinddir(dirhan);
void
closedir(dirhan);
const char *path;
DIR *dirhan;
DESCRIPTION
These are UNIX compatible directory scanning calls. After opening a
directory with opendir, you may scan it with successive calls to
readdir until NULL is returned, then either rewinddir it for a
rescan, or closedir it when done. The DIR structure is private to
the library. Valid fields within struct direct are d_name (the file
name), and d_namlen (the length of the file name, not usually
needed). You can chdir into the directory and stat each entry to
obtain additional information. Note that while the UNIX directory
scanning routines will not be as efficient as the Amiga directory
scanning routines, the UNIX directory scanning routines are portable.
|| NOTE: Unlike the Amiga directory scanning routines that use Amiga
|| File Locks, these calls will automatically deallocate resources if
|| the program terminates. rewinddir's prototype returns an int.
|| This is for internal use only. You should never use rewinddir's
|| return value yourself.
SEE ALSO
chdir
EXAMPLE
#include <stdio.h>
#include <sys/dir.h>
main(int ac, char*av[])
{
DIR *dir;
if (ac == 1)
{
puts("test dir");
exit(1);
}
if (dir = opendir(av[1]))
{
struct direct *entry;
while (entry = readdir(dir))
{
printf("%s\n", entry->d_name);
}
closedir(dir);
}
return(0);
}
dice/_divs,_divu dice/_divs,_divu
FUNCTION
Signed and unsigned long divide (DICE)
DESCRIPTION
DICE uses these assembly level functions whenever it needs to do long
division; they are not callable from C.
INPUTS
D0 32 bit signed/unsigned integer
D1 32 bit signed/unsigned integer
RESULTS
D0 D0 divided by D1
SEE ALSO
_mods, _modu, _muls, _mulu
dice/exit dice/exit
FUNCTION
Exit from a program 'nicely' (ANSI)
SYNTAX
#include <stdlib.h>
(void) exit(code)
DESCRIPTION
exit exits the program and returns the specified exit code. Normally
you pass 0 to indicate no errors, and a positive number to indicate a
program error to the parent. exit closes all stdio file pointers,
low level file descriptors, perhaps a few other things, and then
finally calls _exit with the code. If you use main you should call
exit to exit the program or return an error code from main. If you
use the _main entry point (only for programmers dead set on
optimizing executable size and using only system library calls) you
should use the _exit exit point.
SEE ALSO
main, _main, _exit
EXAMPLE
main(int ac, char *av[])
{
if (ac <= 1) {
puts("Sorry, you must supply a parameter!");
exit(1);
}
puts("Thanks!");
exit(0);
}
dice/_exit dice/_exit
FUNCTION
exit from a program without bothering to release resources (ANSI)
SYNTAX
#include <stdlib.h>
(void) _exit(code)
int code;
DESCRIPTION
_exit exits from a program and returns the specified exit code.
Normally you pass 0 to indicate no errors, a positive number to
indicate a program error to the parent. Note that since auto-init
opened libraries are closed in the startup module (c.o),
automatically opened libraries will be automatically closed for you.
However, any libraries you manually declare the library base variable
for and manually open must be closed by you. You should only call
_exit if you used the _main entry point (instead of the usual main),
and then only after releasing all resources (such as file handles
opened with open).
INPUTS
code int; code is a value that is passed back to
caller
SEE ALSO
main, _main, exit
EXAMPLE
_main()
{
Write(Output(), "Ouch!!\n", 7);
_exit(20); /* 20 - Severe Error */
}
dice/exp dice/exp
FUNCTION
return e to the power of the double quantity (ANSI)
LIBRARY
m.lib
SYNTAX
#include <math.h>
double a = exp(b);
double b;
DESCRIPTION
exp returns e to the power of the floating point quantity.
INPUTS
double b; double floating point value
RESULTS
double a; result double floating point value
SEE ALSO
acos, asin, atan, cos, fabs, log, log10, pow, sin, sqrt, tan facos,
fasin
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = exp(0.25);
printf("exp 0.25 = %lf\n", a);
}
{ /* less accuracy */
float a = fexp(0.25);
printf("exp 0.25 = %lf\n", (double)a);
}
return(0);
}
dice/expand_args dice/expand_args
FUNCTION
expand command line argument wildcards (DICE)
SYNTAX
#include <stdio.h>
int error = expand_args(xac, xav, &ac, &av);
int xac;
const char **xav;
int ac;
char **av;
DESCRIPTION
expand_args is a powerful and convenient function. A few lines of
simple code allow your program to have full wildcard support under
any version of the OS. expand_args takes an argc/argv list and
expands any wildcard arguments by scanning the appropriate directory.
It malloc's however much memory it needs to create the new list and
ignores xav[0] (that is, it just copies it to the returned av[0]
without doing a wildcard expansion). expand_args fills in the ac and
av variables with its own malloc'd version of the argument list, now
completely expanded. There is no limit to the number of files that
may be in this result list (you could conceivably have thousands).
expand_args may be used to expand arbitrary AmigaDOS wildcards and is
not limited to an anchored search. For example, you could specify:
sys:#?/#? in which case a list of a second level files/dirs will be
generated. In the above case, expand_args scans sys, then scans any
sub directories found in sys. Generic AmigaDOS wildcarding is used
and incredibly complex wildcards may be specified. Please note,
however, that any wildcard elements containing #? in combination with
other elements (such as (a|b|c)) will cause huge amounts of stack to
be used and also quite a bit of memory during the scan. expand_args
limits itself to 4K of stack before giving up. Any program that uses
expand_args should be run with at least 8K of stack.
INPUTS
int xac; original argc
char **xav; original argv
int *ac; pointer to new argc
char ***av; pointer to new argv
RESULTS
int error; 0 if all went well, non-zero otherwise
EXAMPLE
#include <stdio.h>
main(int xac, char **xav)
{
int ac, i, error;
char **av;
int error = expand_args(xac, xav, &ac, &av);
for (i = 1; i < ac; ++i) {
printf("%s\n", av[i]);
}
} /* expand_args #?.c */
dice/fabs dice/fabs
FUNCTION
return the absolute value of a double quantity (ANSI)
LIBRARY
m.lib
SYNTAX
#include <math.h>
double a = fabs(b);
double b;
DESCRIPTION
fabs returns the absolute value of a floating point quantity.
INPUTS
float d; float floating point value
RESULTS
int arg; control argument
int r; result, error if less than 0.
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = fabs(-0.25);
printf("fabs -0.25 = %lf\n", a); /* 0.25 */
}
{ /* less accuracy */
float a = ffabs(-0.25);
printf("fabs -0.25 = %lf\n", (double)a);
}
return(0);
}
dice/facos dice/facos
FUNCTON
float arc cosine (UNIX)
LIBRARY
m.lib
SYNTAX
#include <math.h>
float c = facos(d);
float d;
DESCRIPTION
facos returns the arc cosine of a floating point quantity.
INPUTS
float d; float floating point value
RESULTS
result float; floating point value
SEE ALSO
acos, asin, atan, cos, exp, fabs, log, log10, pow, sin, sqrt, tan,
fasin
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = acos(0.25);
printf("acos 0.25 = %lf\n", a); /* 1.318 */
}
{ /* less accuracy */
float a = facos(0.25);
printf("acos 0.25 = %lf\n", (double)a);
}
return(0);
}
dice/fasin dice/fasin
FUNCTION
return arc sine of a float quantity (UNIX)
LIBRARY
m.lib
SYNTAX
#include <math.h>
float c = fasin(d);
float d;
DESCRIPTION
fasin returns the arc sine of a floating point quantity.
INPUTS
float d; float floating point value
RESULTS
float c; result float loating point value
SEE ALSO
acos, asin, atan, cos, exp, fabs, log, log10, pow, sin, sqrt, tan
facos
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = asin(0.25);
printf("asin 0.25 = %lf\n", a); /* 0.2527 */
}
{ /* less accuracy */
float a = fasin(0.25);
printf("asin 0.25 = %lf\n", (double)a);
}
return(0);
}
dice/fatan dice/fatan
FUNCTION
return arc tan of a float quantity (UNIX)
LIBRARY
m.lib
SYNTAX
#include <math.h>
float c = fatan(d); float d;
DESCRIPTION
fatan returns the arc tan of a floating point quantity.
INPUTS
float d; float floating point value
RESULTS
float c; result float floating point value
SEE ALSO
acos, asin, atan, cos, exp, fabs, log, log10, pow, sin, sqrt, tan
facos, fasin
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = atan(0.25);
printf("atan 0.25 = %lf\n", a); /* 0.245 */
}
{ /* less accuracy */
float a = fatan(0.25);
printf("atan 0.25 = %lf\n", (double)a);
}
return(0);
}
dice/fclose dice/fclose
FUNCTION
close a file pointer (ANSI)
SYNTAX
#include <stdio.h>
int error = fclose(fp);
FILE *fp;
DESCRIPTION
fclose flushes any data remaining in the file pointer's output buffer
to the file and then closes the file. The file pointer is no longer
valid. fclose returns any error condition that occured while it was
flushing the buffered data to the file. The file is closed even if
an error occured.
|| NOTE: You can fclose(stdin), fclose(stdout), and fclose(stderr) to
|| save space or detach your process from the console (i.e. allow the
|| console window to be closed).
## WARNING: If you fclose stdin, stdout, and stderr with the
## intention of removing all references to the console window, you
## must put a NULL in your processes pr_ConsoleTask field. Otherwise,
## the console window will be able to close, but your process will
## still have a reference to the now non-existent window. Refer to
## the file_pointer manual page for general information
INPUTS
FILE *F; file pointer
RESULTS
int error; error on fclose, or 0 if none
SEE ALSO
fopen, fread, fwrite, fgets, fputs
dice/fcntl dice/fcntl
FUNCTION
file control on a file (UNIX)
SYNTAX
#include <fcntl.h>
int r = fcntl(fd, req, arg)
int fd;
int req;
int arg;
DESCRIPTION
fcntl may be used to control various aspects of an fd and is a higher
level call than ioctl. Currently, nothing truly significant can be
accomplished by a fcntl call for files. However, fcntl fully
supports programmer simulated file descriptors.
|| NOTE: Refer to the file_descriptor manual page for general
|| information Unlike file pointers and file handles, the file
|| descriptor is checked for validity and if illegal, an error will
|| be returned.
INPUTS
int fd; file descriptor to operate on
int req; request from <fcntl.h> (F_* defines)
int arg; control argument
RESULTS
int r; result, error if less than 0
SEE ALSO
close, creat, fcntl, fdtofh, ioctl, isatty, lseek, mkdir, open, read,
rmdir, unlink, write
dice/fdopen dice/fdopen
FUNCTION
associate a file pointer with an open file descriptor (UNIX)
SYNTAX
#include <stdio.h>
FILE *fp = fdopen(fd, modes);
int fd; char *modes;
DESCRIPTION
fdopen associates an open file descriptor with a file pointer.
|| NOTE: Once fclose is used, the file pointer will also close the
|| file descriptor. Refer to the fopen manual page for a description
|| of available modes. Also, when you use fdopen the file will not be
|| truncated and if you specify mode a for append, the file
|| descriptor must have been opened with the O_APPEND flag. That is,
|| the mode string should be similar to the open flags that were used
|| to open the file descriptor. Refer to the file_pointer manual page
|| for general information
INPUTS
int fd; file descriptor to associated with a new file
pointer
char *modes; modes string, such as "r+".
RESULTS
FILE *fp; new file pointer or NULL if an error occured
SEE ALSO
fopen, fread, fwrite, fgets, fputs
dice/fdtofh dice/fdtofh
FUNCTION
return AmigaDOS file handle for file descriptor (AmigaDOS)
SYNTAX
#include <stdio.h>
BPTR fh = fdtofh(fd);
int fd;
DESCRIPTION
fdtofh returns the AmigaDOS file handle associated with a file
descriptor or NULL if the file descriptor is illegal or simulated.
You may then make AmigaDOS library calls using the file handle.
INPUTS
int fd; file descriptor
RESULTS
BPTR fh; associated file handle or NULL
SEE ALSO
close, creat, fcntl, ioctl, isatty, lseek, mkdir, open, read, rmdir,
unlink, write
EXAMPLE
#include <stdio.h>
main()
{
FILE * fh;
write(1, "Quayle\n", 6);
if( fh = fdtofh(1) ) /* Example Only! */
Write(fh, "Bait\n", 6);
return(0);
}
dice/feof dice/feof
FUNCTION
test a file pointer for End Of File (ANSI)
SYNTAX
#include <stdio.h>
int r = feof(fp);
(MACRO) FILE *fp;
DESCRIPTION
feof returns the EOF status of a file pointer. The status is not
changed by this macro. 0 is returned if no EOF condition exists,
non-zero if an EOF condition exists (not necessarily 1 or -1, just
non-zero). Use clearerr to clear the EOF condition. Note than fseek
and rewind also clear an EOF condition.
INPUTS
FILE *fp; file pointer
RESULTS
int r; 0 if no EOF condition exists, != 0 if an EOF
condition exists (not necessarily 1 or -1).
SEE ALSO
fopen, fclose, fread, fwrite, fgets, fputs, file_pointer
dice/ferror dice/ferror
FUNCTION
return ERROR condition for file pointer (ANSI)
SYNTAX
#include <stdio.h>
int r = ferror(fp); /* MACRO */
FILE *fp;
DESCRIPTION
ferror returns the ERROR status of a file pointer. The status is not
changed by this macro. 0 is returned if no ERROR condition exists,
non-zero if an ERROR condition exists (not necessarily 1 or -1, just
non-zero).
INPUTS
FILE *fp; file pointer
RESULTS
int r; 0 if no ERROR condition exists, != 0 if an ERROR
condition exists (not necessarily 1 or -1).
SEE ALSO
fopen, fclose, fread, fwrite, fgets, fputs, file_pointer
dice/fexp dice/fexp
FUNCTION
return e to the power of the float quantity (UNIX)
LIBRARY
m.lib
SYNTAX
#include <math.h>
float c = fexp(d);
float d;
DESCRIPTION
fexp returns e to the power of the floating point quantity
INPUTS
float d; float floating point value
RESULTS
float c; result float floating point value
SEE ALSO
acos, asin, atan, cos, exp, fabs, log, log10, pow, sin, sqrt, tan,
facos, fasin
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = exp(0.25);
printf("exp 0.25 = %lf\n", a);
printf("exp 0 = %lf\n", (double)exp(0) );
}
{ /* less accuracy */
float a = fexp(0.25);
printf("exp 0.25 = %lf\n", (double)a);
}
return(0);
}
dice/ffabs dice/ffabs
FUNCTION
return the absolute value of a float (UNIX)
LIBRARY
m.lib
SYNTAX
#include <math.h>
float c = ffabs(d);
float d;
DESCRIPTION
ffabs returns the absolute value of a floating point quantity.
INPUTS
float d; float floating point value
RESULTS
int arg; control argument
int r; result, error if less than 0.
SEE ALSO
acos, asin, atan, cos, exp, fabs, log, log10, pow, sin, sqrt, tan,
facos, fasin
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = fabs(-0.25);
printf("fabs -0.25 = %lf\n", a); /* 0.25 */
}
{ /* less accuracy */
float a = ffabs(-0.25);
printf("fabs -0.25 = %lf\n", (double)a);
}
return(0);
}
dice/fflush dice/fflush
FUNCTION
flush buffers to file (ANSI)
SYNTAX
#include <stdio.h>
int error = fflush(fp);
FILE *fp;
DESCRIPTION
fflush writes out any buffered data out to the file descriptor
associated with the file pointer. Normally a file is either
unbuffered, line buffered, or fully buffered; fflush is useful in
the latter two cases as is shown by the example. The function will
return -1 if a write error occured, 0 if no error occured.
|| NOTE: Refer to the file_pointer manual page for general
|| information.
INPUTS
FILE *fp; file pointer
RESULTS
int error; 0 if no error, -1 on error.
SEE ALSO
fopen, fclose, fread, fwrite, fgets, fputs
EXAMPLE
/*
* Since text to stdout is normally line buffered,
* if we do not write out a newline '\n' then the
* line is still buffered in memory and we have to
* fflush() to write it out.
*/
#include <stdio.h>
main()
{
char buf[256];
printf("Enter a number -");
fflush(stdout);
fgets(buf, sizeof(buf), stdin);
printf("Munch Munch...");
fflush(stdout);
sleep(1);
puts("Thanks!");
}
dice/fgetc,getc dice/fgetc,getc
FUNCTION
fgetc: get a single character (ANSI)
getc: get a single character from a file pointer (ANSI)
SYNTAX
#include <stdio.h>
int c = fgetc(fp);
int c = getc(fp); /* MACRO */
FILE *fp;
DESCRIPTION
getc and fgetc both read a single character from a file pointer. The
value returned is actually an int because EOF (-1) must be
differentiated from a 255. Each returns an integer 0-255 or EOF (-1)
if an end of file occurs.
|| NOTE: Refer to the file_pointer manual page for general
|| information.
INPUTS
FILE *fp; file pointer
RESULTS
int c; character 0 to 255, or EOF (-1).
SEE ALSO
putc, fputc, fread, fwrite
EXAMPLE
/*
* copy stdin to stdout using getc/putc. Normally
* one uses fread/fwrite, but I'll save that for the
* fread manual page.
* Note that I output the initial message to stderr so
* it does not get stuck into stdout in case the user
* has redirected stdout.
*/
#include <stdio.h>
main()
{
int c;
fputs("Type a couple of lines, then ^\\ (EOF)\n",
stderr);
while ((c = getc(stdin)) != EOF)
{
putc(c, stdout);
}
return(0);
}
dice/fgetpos dice/fgetpos
FUNCTION
get current file position (ANSI)
SYNTAX
#include <stdio.h>
int error = fgetpos(fp, &pos);
fpos_t pos;
DESCRIPTION
fgetpos returns the current seek position and is roughly equivalent
to ftell. fgetpos is a new ANSI call to better support C compilers
that use 16 bit integers. DICE uses 32 bit integers so fgetpos is
not so useful. fgetpos takes a file pointer and the address of a
fpos_t type (a long). It fills the fpos_t variable with the current
file position and returns 0 if all went well, non-zero if an error
occured.
|| NOTE: Refer to the file_pointer manual page for general
|| information.
INPUTS
FILE *fp; file pointer
fpos_t *pos; pointer to an fpos_t type that the position is
loaded into.
RESULTS
int error; 0 if no error, non-zero on error
SEE ALSO
ftell, rewind, fseek, rewind
EXAMPLE
/*
** Return the length of the file specified on the
** command line. */
#include <stdio.h>
main(int ac, char*av[])
{
FILE *fp;
fpos_t off;
if (ac == 1) {
puts("Expected a filename argument");
exit(1);
}
fp = fopen(av[1], "r");
if (fp == NULL) {
printf("Unable to open %s\n", av[1]);
exit(5);
}
fseek(fp, 0L, SEEK_END);
if (fgetpos(fp, &off)) {
puts("Error getting file position");
exit(20);
}
fclose(fp);
printf("File %s is %d bytes long\n", av[1], off);
return(0);
}
dice/fgets dice/fgets
FUNCTION
get a line from a file pointer (ANSI)
SYNTAX
#include <stdio.h>
char *ptr = fgets(buf, maxlen, fp);
char *buf;
int maxlen;
FILE *fp;
DESCRIPTION
fgets gets a line from the specified file pointer, returning the
first argument (buf) or NULL if an error or EOF occurs. fgets stores
the line in buf, up to maxlen characters. This maximum includes a
terminating newline '\n' and NULL '\0'. If more than maxlen-1
characters are in the line fgets will terminate operation and put a
NULL as the last character (so the buffer will still be a valid
string). It is common to become confused by these functions:
gets, puts
These functions strip newline on input, add newline on output.
gets works on stdin, puts on stdout.
fgets, fputs
These functions leave newlines alone on input, don't add to the
output. Any file pointer, including stdin and stdout may be
specified.
|| NOTE: Refer to the file_pointer manual page for general
|| information.
INPUTS
char *buf; buffer
int maxlen; maximum buffer size
FILE *fp; file pointer
RESULTS
char *ptr; buf if all is well, or NULL if error or EOF
SEE ALSO
gets, puts, fputs, fread, getc, fgetc
EXAMPLE
#include <stdio.h>
main()
{
unsigned char buf[128];
short i;
printf("Enter a line - ");
fflush(stdout);
if (fgets(buf, sizeof(buf), stdin) == NULL)
exit(1);
printf("In Hex: ");
for (i = 0; buf[i]; ++i) printf(" %02x", buf[i]);
puts("");
return(0);
}
dice/fhprintf dice/fhprintf
FUNCTION
formatted printing to a DOS file handle (AmigaDOS)
SYNTAX
#include <stdio.h>
int n = fhprintf(fh, ctl, ...);
BPTR fh;
const char *ctl;
DESCRIPTION
fhprintf provides a method of using DICE's pfmt lib to do formatted
printing to a file handle instead of a stdio file pointer. Output is
unbuffered and thus not very efficient, but the call can be extremely
useful when debugging libraries and such. If you have just a few
things to print, and want to save the space the entire stdio package
takes, you could use this function and _main.
INPUTS
BPTR fh; DOS file handle
const char *ctl; format string, see printf()
RESULTS
int n; number of characters output
SEE ALSO
printf, sprintf, vsprintf, fprintf, vfprintf, _main
EXAMPLE
void _main(int ac, char**av)
{
fhprintf(Output(), "The answer is %d!\n", 42);
}
dice/file_descriptor dice/file_descriptor
FUNCTION
file descriptor
DESCRIPTION
A file descriptor is the lowest portable access to the file system a
C program may make. File descriptors are used with open, read,
write, close, etc. A file descriptor is unbuffered (that is, every
operation goes to the kernel and does not get buffered locally).
|| NOTE: Remember that a file descriptor is different from a stdio
|| file pointer (see the file_pointer manual page) and an AmigaDOS
|| file handle.
dice/fileno dice/fileno
FUNCTION
return file descriptor given a file pointer (UNIX)
SYNTAX
#include <stdio.h>
int fd = fileno(fp); /* MACRO */
FILE *fp;
DESCRIPTION
The fileno macro returns the file descriptor (open, close, read,
write) associated with the file pointer (fopen, fclose, fread,
fwrite). This is still not the AmigaDOS file handle; to get that you
must use the fdtofh call.
## WARNING: If you use the file descriptor of a file pointer the file
## pointer will get its seek position confused. Additionally, there
## might be unflushed data in the file pointer's buffers that has not
## been written out to the file descriptor yet. There also might be
## unread input on the file pointer's input buffers already read from
## the file descriptor.
|| NOTE: Refer to the file_pointer manual page for general
|| information.
INPUTS
FILE *fp; file pointer
RESULTS
int fd; associated file descriptor
SEE ALSO
fdopen, fopen, fclose, open, close
dice/file_pointer dice/file_pointer
FUNCTION
STDIO file_pointer (ANSI)
DESCRIPTION
A file pointer is the basis for stdio, a standard file management
package available across all versions of C. If you stick to the
standard functions, your program should work on any machine that can
compile C.
The specific Amiga implementation builds file pointers (type "FILE
*") on top of file descriptors (type "int"; see the file_descriptor
manual page). File pointers have a layer of buffering (good if you
use many small reads and writes), while file descriptors pass
requests directly to AmigaDOS. Note that a stdio file pointer is not
a file descriptor nor is a AmigaDOS file handle. You may call only
stdio routines (fopen, fclose, fread, fwrite, etc.) with file
pointers.
Some C implementations flush stdout whenever stdin is read. DICE
does not do this.
dice/fopen dice/fopen
FUNCTION
open a file and create a file pointer (ANSI)
SYNTAX
#include <stdio.h>
FILE *fp = fopen(filename, modes)
char *filename;
char *modes;
DESCRIPTION
fopen is the grand master of stdio: it opens and possibly creates a
file and returns a new file pointer for use by the program. The first
argument is the file to open, the second is a string containing one
or mode characters defined as follows:
Mode : Usage
=====+======================================================================
r : open for reading, the file must already exist
-----+----------------------------------------------------------------------
w : open for writing, the file is created if it does not exist,
: truncated if it does
-----+----------------------------------------------------------------------
a : open for append, writes always append to the file.
-----+----------------------------------------------------------------------
a : the file starts out positioned at the end instead of at the
: beginning. This mode also creates the file but only if it does not
: already exist.
-----+----------------------------------------------------------------------
r+ : also allows writing to the file in addition to reading
-----+----------------------------------------------------------------------
w+ : also allows reading from the file
-----+----------------------------------------------------------------------
b : open for binary read/write, else the file is assumed to contain
: text (this is ignored by DICE since there is no difference on the
: Amiga).
-----+----------------------------------------------------------------------
All combinations except "rw" are allowed. One uses "r+" or "w+"
instead of "rw". By the above description "r+" is used to update an
existing file while "w+" is used to create a new file and then allow
reads as well as writes to it. "wa" is equivalent to creating a new
file and then appending to it. "r+a" is equivalent to appending to an
already existing file. Other examples of valid modes combinations:
"r+b", "w+b", "rb", "wb", "ab", "w", "r", "r+", "a", etc...
|| NOTE: Refer to the file_pointer manual page for general
|| information.
INPUTS
char *filename; file name to open
char *modes; open modes string
RESULTS
FILE *fp; new file pointer
SEE ALSO
fdopen, fclose, open, close
EXAMPLE
#include <stdio.h>
main()
{
FILE *fp;
char * filename = "t:XX";
char * why = "I don't do windows\n";
fp = fopen(filename, "wb");
if( fp ) {
fwrite(why, 1, strlen(why), fp);
fwrite(why, strlen(why), 1, fp);
fclose( fp );
} else {
printf("Can't open file %s\n", filename);
}
return(0);
}
dice/fputc,putc dice/fputc,putc
FUNCTION
fputc: write a single character (ANSI)
putc: write a single character (ANSI)
SYNTAX
#include <stdio.h>
int c = fputc(c, fp);
int c = putc(c, fp); /* MACRO */
FILE *fp;
DESCRIPTION
fputc writes a single character to a file pointer. If all goes well
the character is returned, else EOF is returned. fputc is a function
call while putc is a macro
|| NOTE: Refer to the file_pointer manual page for general
|| information.
INPUTS
int c; character to write
FILE *fp; file pointer
RESULTS
int c; character written (same as first argument) or EOF
if error.
SEE ALSO
getc, putc, fputc, fread, fwrite, puts, fputs, gets, fgets
EXAMPLE
/*
* copy stdin to stdout using fgetc/fputc. Normally one
* uses fread/fwrite, but I'll save that for the fread
* manual page. note that I output the initial message
* to stderr so it does not get stuck into stdout in
* case the user has redirected stdout.
*/
#include <stdio.h>
main()
{
int c;
fputs("Type a couple of lines, then ^\\ (EOF)\n",
stderr);
while ((c = fgetc(stdin)) != EOF)
{
fputc(c, stdout);
}
return(0);
}
dice/fputs,puts dice/fputs,puts
FUNCTION
fputs: write a string to a file pointer (ANSI)
puts: then write a string to stdout, appending newline (ANSI)
SYNTAX
#include <stdio.h>
int error = fputs(s, fp);
int error = puts(s);
const char *s;
FILE *fp;
DESCRIPTION
fputs writes a string to a file pointer all the way up to, but not
including, the NULL. puts does the same thing but to stdout, and
puts additionally writes a newline out.
|| NOTE: Refer to the file_pointer manual page for general
|| information.
It is common to get confused between fputs and puts. Remember that
puts adds a newline to the output while fputs does not. gets strips
the newline from an input line while fgets does not.
INPUTS
char *s; string to write
FILE *fp; file pointer
RESULTS
int error; 0 or positive if all went ok, else negative. Note
that unlike printf() routines the numberr of
chars written out is NOT returned.
SEE ALSO
getc, putc, fputc, fread, fwrite, gets, fgets
EXAMPLE
#include <stdio.h>
main()
{
/* note newline */
fputs("This is a test of fputs\n", stdout);
puts("This is a test of puts"); /* note lack of */
puts("That's it!");
return(0);
}
dice/fseek dice/fseek
FUNCTION
seek within a file pointer (ANSI)
SYNTAX
#include <stdio.h>
int error = fseek(fp, offset, how);
FILE *fp;
long offset;
int how;
DESCRIPTION
fseek changes the current seek position within a file. Offset is
interpreted according to the how argument:
: :
=========+===+=======================================================
SEEK_SET : 0 : skip to position relative to beginning of file
---------+---+-------------------------------------------------------
SEEK_CUR : 1 : skip to position relative to current position in file
---------+---+-------------------------------------------------------
SEEK_END : 2 : skip to position relative to end of file.
---------+---+-------------------------------------------------------
So, for example, one may seek to the beginning of a file by fseek(fp,
0L, SEEK_SET);, to the end of the file by fseek(fp, 0L, SEEK_END);.
Calling getc at this time would return an immediate EOF. You can
skip characters in a file with something like fseek(fp, 5L,
SEEK_CUR); which skips 5 characters. Note that when seeking relative
to the end of the file, negative offsets are used. For example, to
seek to the very last character in the file you would use fseek(fp,
-1L, SEEK_END); fseek returns 0 on success, a negative number on
ERROR. A common mistake is to expect fseek to return the new
position of the file but this is not what is returned. Use ftell or
fgetpos to determine the current offset into a file.
|| NOTE: Refer to the file_pointer manual page for general
|| information fseek flushes any buffered write data before seeking.
INPUTS
FILE *fp; file pointer to seek
long offset; relative offset, depending on how
int how; 0, 1, or 2 (absolute, relative, end- relative)
RESULTS
int error; Error code from operation
SEE ALSO
ftell, fgetpos, fsetpos, rewind
EXAMPLE
see fopen for an example
dice/fread dice/fread
FUNCTION
read data from a file pointer (ANSI)
SYNTAX
#include <stdio.h>
size_t robjs = fread(buf, objsize, nobjs, fp);
void *buf; size_t objsize; size_t nobjs;
FILE *fp;
DESCRIPTION
fread reads an arbitrary number of objects from a file pointer into
the specified buffer and returns the actual number of objects read.
If the return value robjs is not equal to nobjs then fread was unable
to read the requested number of objects due to either a read error or
an EOF condition. If the file is already completely exhausted fread
simply returns 0. Having two size arguments, an object size and a
number of objects, simplifies the reading of structure arrays off
disk.
|| NOTE: To use fread to read an arbitrary number of bytes one
|| normally uses the form: r = fread(buf, 1, n, fp); that is, n
|| objects of size 1. fread will attempt to read objsize * nobjs
|| bytes into the specified buffer.
INPUTS
void *buf; buffer to load data into
size_t objsize; size of one object
size_t nobjs; number of objects to read
FILE *fp; file pointer to read objects from
RESULTS
size_t robjs; number of objects actually read or 0 if EOF or
ERROR.
SEE ALSO
fwrite, fopen, fclose, fseek, ftell, rewind
dice/free dice/free
FUNCTION
free memory allocated by calloc, malloc, or strdup (ANSI)
SYNTAX
#include <stdlib.h>
void free(ptr);
void *ptr;
DESCRIPTION
free frees memory allocated by calloc, malloc, or strdup.
|| NOTE: It is illegal to free(NULL). If free is given an illegal
|| pointer or NULL, it will freeze the process by calling wait(0L).
INPUTS
void *ptr; pointer to memory to free
SEE ALSO
malloc, calloc, strdup
EXAMPLE
see calloc example
dice/freopen dice/freopen
FUNCTION
reopen a new file using an existing file pointer, the existing file
is closed before it is reused (ANSI)
SYNTAX
#include <stdio.h>
FILE *fp = freopen(filename, modes, ofp)
char *filename;
char *modes;
FILE *ofp;
DESCRIPTION
freopen works exactly like fopen but takes an additional argument, a
file pointer to reuse. This file pointer, ofp, must reference a valid
open file. freopen will close out ofp then reuse the descriptor to
open the new file, returning ofp (fp == ofp) on success, NULL on
failure. If the freopen fails NULL is returned and the original file
pointer is still closed, but not freed so you may call freopen again
with the same ofp, even though it has already been closed. Refer to
the fopen manual page for information on the modes string. freopen is
often used to change a program's stdin, stdout, or stderr though to
be frank, using a separate file pointer is normally much more
modular.
## WARNING: ANSI does not specify that the ofp can be used in a
## second freopen if the first freopen using ofp fails (returns
## NULL). Many implementations free the file pointer. This just might
## be the proper way of doing things but we don't know. We suggest
## you do not use DICE's feature in that respect as we might have to
## change it back to free ofp if the new file is unopenable.
|| NOTE: Refer to the file_pointer manual page for general
|| information
INPUTS
char *filename; file name to open
char*modes; open modes string
FILE *ofp; open file pointer to reuse
RESULTS
FILE *fp; same as ofp if the new open worked, NULL
otherwise
SEE ALSO
fdopen, fopen, fclose, open, close
EXAMPLE
/*
* re-open stdin to an Amiga console device
*/
#include <stdio.h>
#include <assert.h>
main()
{
char buf[256];
assert(freopen("CON:0/0/320/100/freopen-in", "r",
stdin));
assert(freopen("CON:320/0/320/100/freopen-out", "w",
stdout));
/*
* set to line buffered
*/
setvbuf(stdin, NULL, _IOLBF, 0);
setvbuf(stdout, NULL, _IOLBF, 0);
puts("Type a (short) line in the second window");
gets(buf);
fclose(stdin);
fclose(stdout);
fprintf(stderr, "Your line was: %s\n", buf);
return(0);
}
dice/fsetpos dice/fsetpos
FUNCTION
set position within file pointer (nearly equivalent to fseek
absolute) (ANSI)
SYNTAX
#include <stdio.h>
int error = fsetpos(fp, &pos);
FILE *fp; fpos_t pos;
DESCRIPTION
fsetpos is a nearly useless call that is essentially the same as
fseek(fp, (long)pos, 0); fsetpos seeks within a file pointer to the
absolute position specified by an fpos_t type. The address of an
fpos_t object is passed to fsetpos. Normally one saves the current
seek position into an fpos_t type using the fgetpos function, then
seeks back using the fsetpos function. In this way the programmer
need not make any direct reference to the contents of the fpos_t
type.
INPUTS
FILE *fp; file pointer to seek
fpos_t *pos; pointer to fpos_t type previously initialized by
a fgetpos() call.
RESULTS
int error; 0 if no error, < 0 if error
SEE ALSO
ftell, fsetpos, fseek, rewind
EXAMPLE
/*
* get a line, save current position, get rest of
* file, go back to saved position, retrieve line
* again and print again.
*/
#include <stdio.h>
main(int ac, char*av[])
{
FILE *fp;
fpos_t save_pos;
int count;
char buf[256];
if (ac == 1)
{
puts("Expected textfile argument");
exit(1);
}
fp = fopen(av[1], "r");
if (fp == NULL)
{
printf("Unable to open %s\n", av[1]);
exit(1);
}
for (count = 0; fgets(buf, sizeof(buf), fp);
++count)
{
if (count == 0) /* just before second line */
fgetpos(fp, &save_pos);
fprintf(stdout, "%-3d: %s", count + 1, buf);
}
if (count < 2)
{
puts("not enough lines in file for example!");
exit(1);
}
puts("--end of file, now seeking back to line 2--");
fsetpos(fp, &save_pos);
if (fgets(buf, sizeof(buf), fp) == NULL)
{
puts("error!");
exit(1);
}
fprintf(stdout, "%-3d: %s", 2, buf);
fclose(fp);
return(0);
}
dice/fstat dice/fstat
FUNCTION
stat a file descriptor (UNIX)
SYNTAX
#include <sys/stat.h>
int error = fstat(fd, &stat_buf);
struct stat stat_buf;
DESCRIPTION
fstat is a UNIX-compatible call that returns information pertaining
to the file represented by an open file descriptor. See stat for
information on the struct stat fields.
|| NOTE: fstat works just like stat except you provide a UNIX file
|| descriptor (not an AmigaDOS File Handle).
|| Under 2.0, ExamineFH is used. Under 1.3, the original path used
|| to open the file will be stat'd, which ends up scanning the
|| directory if the file was open for exclusive access.
INPUTS
int fd; file descriptor to stat
struct stat *sbuf;
address of stat structure that will be filled in
RESULTS
int error; 0 on success, < 0 on error
SEE ALSO
chdir
EXAMPLE
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
main(int ac, char**av)
{
int r, fd;
struct stat stat_buf;
if (ac == 1) {
puts("Expected a file name");
exit(1);
}
fd = open(av[1], O_RDONLY );
if( fd ) {
r = fstat(fd, &stat_buf);
if (r < 0)
printf("Can't stat fd=%d\n", fd);
else {
printf("File is %d bytes\n", stat_buf.st_size);
printf("modified %s", ctime(&stat_buf.st_ctime));
}
close(fd);
}
return(0);
}
dice/ftell dice/ftell
FUNCTION
return current position within file pointer (ANSI)
SYNTAX
#include <stdio.h>
long pos = ftell(fp);
FILE *fp;
DESCRIPTION
ftell returns the current absolute seek offset within a file pointer.
INPUTS
FILE *fp; file pointer retrieve seek position from
RESULTS
long pos; current absolute seek position in file
SEE ALSO
ftell, fgetpos, fsetpos, fseek, rewind
EXAMPLE
/*
* get a line, save current position, get rest of file,
* go backto saved position, retrieve line again and
* print again.
* like fsetpos() example but uses ftell()/fseek()
* instead
*/
#include <stdio.h>
main(int ac, char**av)
{
FILE *fp;
long save_pos;
int count;
char buf[256];
if (ac == 1)
{
puts("Expected textfile argument");
exit(1);
}
fp = fopen(av[1], "r");
if (fp == NULL)
{
printf("Unable to open %s\n", av[1]);
exit(1);
}
for (count = 0; fgets(buf, sizeof(buf), fp); ++count)
{
if (count == 0) /* just before second line */
save_pos = ftell(fp);
fprintf(stdout, "%-3d: %s", count + 1, buf);
}
if (count < 2)
{
puts("not enough lines in file for example!");
exit(1);
}
puts("--end of file, now seeking back to line 2--");
fseek(fp, save_pos, SEEK_SET);
if (fgets(buf, sizeof(buf), fp) == NULL)
{
puts("error!");
exit(1);
}
fprintf(stdout, "%-3d: %s", 2, buf);
fclose(fp);
return(0);
}
dice/fwrite dice/fwrite
FUNCTION
write data to a file pointer (ANSI)
SYNTAX
#include <stdio.h>
size_t robjs = fwrite(buf, objsize, nobjs, fp);
const void *buf;
size_t objsize;
size_t nobjs;
FILE *fp;
DESCRIPTION
fwrite writes the specified number of objects to a file pointer from
the specified buffer and returns the actual number of objects written
or 0 or -1 depending on the error. If the return value robjs is not
equal to nobjs then a write error occured. Having two size arguments,
an object size and number of objects, simplifies the reading of
structure arrays off disk.
|| NOTE: To use fwrite to read an arbitrary number of bytes one
|| normally uses the form "r = fwrite(buf, 1, n, fp);", that is, n
|| objects of size 1.
INPUTS
void *buf; buffer to copy data from
size_t objsize; size of one object
size_t nobjs; number of objects to write
FILE *fp; file pointer to read objects from
RESULTS
size_t robjs; number of objects actually written (0 or EOF on
error)
SEE ALSO
fread, fopen, fclose, fseek, ftell, rewind
dice/getchar dice/getchar
FUNCTION
get character from stdin (ANSI)
SYNTAX
#include <stdio.h>
int c = getchar(); /* MACRO */
DESCRIPTION
getchar returns the next available character on stdin or EOF if no
more characters are available. getchar is equivalent to getc(stdin).
|| NOTE: Refer to the file_pointer manual page for general
|| information.
INPUTS
none
RESULTS
int c; character 0 to 255, or EOF (-1) returned from
stdin
SEE ALSO
putc, putchar, fputc, fread, fwrite, getc
EXAMPLE
/*
* copy stdin to stdout using getchar/putchar. Normally
* one uses fread/fwrite, but I'll save that for the
* fread manual page.
* Note that I output the initial message to stderr
* so it does not get stuck into stdout in case the
* user has redirected stdout.
*
* See getc manual page for equivalent example using
* getc/putc
*/
#include <stdio.h>
main()
{
int c;
fputs("Type a couple of lines, then ^\\ (EOF)\n",
stderr);
while ((c = getchar()) != EOF)
{
putchar(c);
}
return(0);
}
dice/getcwd dice/getcwd
FUNCTION
get current working directory (UNIX)
SYNTAX
#include <stdio.h>
char *path = getcwd(buf, max);
non-standard call
DESCRIPTION
getcwd gets the current working directory and puts it into the
specified buffer buf. If buf is NULL it will be malloc'd
automatically. The parameter buf is returned (or the malloc'd buffer
if you passed NULL for buf). The parameter max specifies the maximum
length of the path including the terminating NULL character. NULL is
returned if any error occurs (such as malloc failing)
INPUTS
char *buf; buffer to place current directory path into or
NULL if you want getcwd to allocate one
int max; maximum size of buffer
RESULTS
char *path; returns allocated buffer if you passed NULL for
buf, else returns the first argument. Returns
NULL on error.
SEE ALSO
chdir
EXAMPLE
#include <stdio.h>
char buf[512];
main(int ac, char**av)
{
getcwd(buf, sizeof(buf));
printf("Current directory is: %s\n", buf);
return(0);
}
dice/getenv dice/getenv
FUNCTION
get environment variable (ANSI)
SYNTAX
#include <stdlib.h>
char *var = getenv(const char *name);
DESCRIPTION
getenv searches for and returns the ENV: enviroment variable
requested. getenv will cache variables so that requesting the same
variable repetitously does not allocate a new memory buffer. getenv
allocates a buffer for each variable returned, so you do not have to
copy the return value from getenv. This memory is free'd on program
exit. Do not attempt to free a getenv'd variable!!
INPUTS
char *name; Name of enviroment variable, on the Amiga this is
not case sensitive. On UNIX systems it is.
RESULTS
char *var; Contents of enviroment variable or NULL if the
variable could not be found.
EXAMPLE
#include <stdio.h>
#include <stdlib.h>
main(int ac, char**av)
{
char *dccopts = getenv("DCCOPTS");
if (dccopts)
printf("DCCOPTS = %s\n", dccopts);
else
printf("You do not have a DCCOPTS enviroment\
variable!\n");
return(0);
}
dice/getfnl dice/getfnl
FUNCTION
get file name list: scan directory, return list of files that match
the optional wildcard (DICE)
SYNTAX
#include <stdlib.h>
int n = getfnl(pat, buf, bufsize, attr);
const char *pat;
char *buf;
int bufsize;
int attr;
DESCRIPTION
getfnl scans the specified anchored AmigaDOS pattern and fills the
specified buffer (up to bufsize bytes) with file names separated by a
NULL character (\0), ending the list with a double NULL (\0\0).
getfnl returns the number of files/dirs in the buffer or -1 if there
is not enough room The pattern pat is an AmigaDOS pattern such as
"df0:#?.c". The parameter buf is a buffer of bufsize bytes. The
parameter attr determines what kinds of files are valid: 0 for
normal files only, 1 for files and directories
|| NOTE: getfnl exists for compatibility only; expand_args is a much
|| better function function to use if you want a list of files &
|| dirs.
INPUTS
const char *pat; pattern to scan for (anchored)
char *buf; buffer to put results in
int bufsize; size of buffer
int attr; attribes (0 or 1)
RESULTS
int n; number of file names in buffer or -1 on error
SEE ALSO
strbpl, expand_args
EXAMPLE
#include <stdio.h>
char Buf[4096];
main(int ac, char**av)
{
int n;
if (ac != 2)
{
puts("Expected an anchored wildcard such as '#?'");
exit(1);
}
n = getfnl(av[1], Buf, sizeof(Buf), 1);
{
char *ptr = Buf;
while (*ptr)
{
/* look for \0\0 */
puts(ptr);
ptr += strlen(ptr) + 1;
/* skip first \0 */
}
}
return(0);
}
dice/GetHead,GetTail,GetSucc,GetPred dice/GetHead,GetTail,GetSucc,GetPred
FUNCTION
Manipulate EXEC style lists (DICE)
SYNTAX
#include <lists.h>
struct Node *node = GetHead(list);
struct Node *node = GetTail(list);
struct Node *node = GetSucc(oldNode);
struct Node *node = GetPred(oldNode);
const struct Node *oldNode;
const struct List *list;
DESCRIPTION
These functions allow scanning of EXEC style lists (which are also
useful for many programs having nothing to do with EXEC). GetHead
returns the first node in a list or NULL if the list is empty;
GetTail returns the last node in a list or NULL if the list is empty;
GetSucc returns the next node in a list (given some intermediate
node) or NULL when we reach the end of the list GetPred returns the
previous node in a list before some intermediate node or NULL when we
reach the beginning of the list
|| NOTE: These are DICE functions and do not exist outside of DICE,
|| though they could be easily written.
INPUTS
struct List *list;
list to get head or tail node from
struct Node *oldNode;
node from which to get relative successor or
predecessor from
RESULTS
struct Node *node;
returned node or NULL
EXAMPLE
/*
* A simple symbol create/delete/list program.
* (Note: for a real symbol table you'd want
* to use hash tables)
*/
#include <lists.h> /* non-standard header file */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct List List;
typedef struct Node Node;
List SymList;
void AddSymbol(char *);
void DelSymbol(char *);
Node *FindSymbol(char *);
main()
{
char buf[256];
char symBuf[256];
short notDone = 1;
NewList(&SymList);
puts("(return for help)");
while (notDone)
{
printf("Enter Command: ");
fflush(stdout);
if ( fgets(buf, sizeof(buf), stdin) == NULL)
break;
switch(buf[0])
{
case 'a': if (sscanf(buf + 1,"%s",symBuf)== 1)
AddSymbol(symBuf);
break;
case 'd': if (sscanf(buf + 1,"%s",symBuf)== 1)
DelSymbol(symBuf);
break;
case 'l': { Node *node;
for (node = GetHead(&SymList); node;
node = GetSucc(node))
puts(node->ln_Name);
}
break;
case 'q': notDone = 0;
break;
default: puts("<return> -help ");
puts("a name-add symbol");
puts("d name-delete symbol");
puts("l -list symbols");
puts("q -quit");
break;
}
}
puts("bye!");
return(0);
}
void AddSymbol(name)
char *name;
{
Node *node;
if (FindSymbol(name))
{
puts("already exists!");
exit(1);
}
if (node = malloc(sizeof(Node)))
{
AddTail(&SymList, node);
node->ln_Name = strdup(name);
/* bad code, not checking */
/* for error result! */
}
}
void DelSymbol(name)
char *name;
{
Node *node;
if (node = FindSymbol(name))
{
Remove(node); /* take out of list */
free(node->ln_Name); /* free name */
free(node); /* free node last */
puts("ok");
}
else
{
puts("Couldn't find it!");
} }
Node * FindSymbol(name)
char *name;
{
Node *node;
for (node = GetHead(&SymList); node;
node = GetSucc(node))
{
if (strcmp(node->ln_Name, name) == 0)
return(node);
}
return(NULL);
}
dice/gets dice/gets
FUNCTION
get a line from stdin (ANSI)
SYNTAX
#include <stdio.h>
char *ptr = gets(buf);
char *buf;
DESCRIPTION
gets takes a line from stdin and places it into your buffer. A null
(\0) is placed in the buffer instead of the newline (\n). While the
function can be convenient, if your buffer is not large enough, you
loose. See fgets for a more reasonable function.
gets, puts
These functions strip newline on input, add newline on output.
gets works on stdin, puts on stdout.
fgets, fputs
These functions leave newlines alone on input, don't add to the
output. Any file pointer, including stdin and stdout may be
specified.
|| NOTE: Refer to the file_pointer manual page for general
|| information.
INPUTS
char *buf; buffer, must be able to maximum possible line
RESULTS
char *ptr; buf if all is well, or NULL if error or EOF
SEE ALSO
puts, fputs, fgets, fread, getc, fgetc
EXAMPLE
#include <stdio.h>
main()
{
char buf[128];
printf("Enter a line - ");
fflush(stdout);
if (gets(buf) == NULL) // Enter a long line to crash
exit(1);
printf("Your line was: %s\n", buf);
return(0);
}
dice/isalnum,isalpha,iscntrl,isdigit,isgraph,islower,isprint,ispunct,isspace,isupper,isxdigit
FUNCTION
Test a character for assorted attributes (ANSI)
SYNTAX
#include <ctype.h>
int r = isxxxxx(c);
int c;
|| NOTE: These are MACROS if you #include <ctype.h>, function calls
|| if you do not.
DESCRIPTION
These function return non-zero (true) if the test is true, and zero
(false) if not.
|| NOTE: When a non-zero value is returned, this value might be
|| anything other than zero. It is not necessarily a 1. It is
|| guaranteed to fit in a short, however, and still remain
|| non-zero.
||
|| Characters in the -1 to 255 range are valid inputs. Characters
|| less than -1 or larger than 255 are illegal and the results will
|| be random. If you are passing a CHAR, you must cast it to an
|| UNSIGNED CHAR first. EOF is a valid input, and always returns
|| false
isalpha Returns non-zero if the character is a letter in the alphabet
(a-z, A-Z).
isalnum Returns non-zero if the character is alphanumeric (a-z, A-Z,
0-9).
iscntrl Returns non-zero if the character is a control character (decimal
0 to 31).
isdigit Returns non-zero if the character is a digit ('0' through '9').
isgraph Returns non-zero if the character is printable and not a space.
isgraph is the same as isprint, but with the space character
excluded from the printable set.
islower Returns non-zero if the character is a lower case letter 'a' -
'z'.
isprint
Returns non-zero if the character is printable. isprint is the same
as isgraph, but with the space character included in the printable
set.
ispunct Returns non-zero if the character is any sort of punctuation,
including puntuation in the extended ASCII range. Basically, if
it is not a control character, alpha or a digit, it is
punctuation.
isspace Returns non-zero if the character is any sort of white space.
Included are space, shifted space, line feed (lf), form feed
(ff), carriage return (cr), tab, and vertical tab.
isupper Returns non-zero if the character is an upper case letter 'A'
-'Z'.
isxdigit Returns non-zero if the character is a valid hexadecimal digit
'0' - '9', 'a' - 'f', or 'A' - 'F'.
These macros use a lookup table. One table handles the eight
most common functions. A second table handles ispunct, isxdigit
and isprint. It saves space if you reference only one table.
There is space in the second table if you wish to add your own
tests (you'll have to recompile the library source code).
INPUTS
int c; character that we are checking
RESULTS
int r; 0 if the check failed, non-zero if the check is
true
SEE ALSO
tolower, toupper
#include <stdio.h>
#include <ctype.h>
main()
{
int c;
for( c=0; c<256; c++) {
if( (c & 31) == 0 ) /* 32 per line */
printf("\n%02x: ", c);
if( isprint( c ) )
printf("%c", c ); /* character */
else
printf("%c", 127 ); /* placeholder */
}
printf("\n");
for( c=0; c<256; c++) {
if( (c & 31) == 0 ) /* 32 per line */
printf("\n%02x: ", c);
if( ispunct( c ) )
printf("x"); /* true */
else
printf("-"); /* false */
}
printf("\n");
return( 0 );
}
dice/isatty dice/isatty
FUNCTION
Test if a a file descriptor is a TTY (UNIX)
SYNTAX
#include <ctype.h>
int r = isatty(fd); int fd;
DESCRIPTION
isatty returns TRUE (1) if the file descriptor is associated with a
console, FALSE (0) if not, or -1 if an error condition occurs (such
as illegal file descriptor).
|| NOTE: The standard input (0), standard output (1), and standard
|| error (2) can all return different values for isatty depending on
|| how the program is redirected. A program whose standard in and
|| standard out is redirected may still have a standard error that is
|| connected to the console. Refer to the file_descriptor manual page
|| for general information. Unlike file pointers and file handles,
|| the file descriptor is checked for validity and will simply return
|| an error if illegal.
INPUTS
int fd; file descriptor
RESULTS
int r; result, 1 if a tty, 0 if not, or -1 if error
SEE ALSO
close, creat, fcntl, fdtofh, getfh, ioctl, lseek, mkdir, open, read,
rmdir, unlink, write
dice/ioctl dice/ioctl
FUNCTION
IO control on file descriptor (UNIX)
SYNTAX
#include <fcntl.h>
int r = ioctl(fd, req, parg1, parg2);
int fd;
int req;
int *parg1;
int *parg2;
DESCRIPTION
ioctl executes an IO control on the file descriptor. Currently no IO
controls are implemented.
INPUTS
int fd; file descriptor
int req; request from <ioctl.h>
int *parg1; address of argument #1
int *parg2; address of argument #2
RESULTS
int r; result, error if < 0.
SEE ALSO
close, creat, fcntl, fdtofh, getfh, isatty, lseek, mkdir, open, read,
rmdir, unlink, write
dice/localtime dice/localtime
FUNCTION
convert time into broken down time (ANSI)
SYNTAX
#include <time.h>
struct tm *tp = localtime(&t);
time_t t;
DESCRIPTION
localtime takes the address of a time_t variable and breaks up the
time into component parts, storing them in a static tm structure.
The address of this structure is returned. Since the broken up time
is stored into a static structure, the structure will get overwritten
on the next call to localtime. The fields of the tm structure are:
struct tm {
int tm_sec; /* 0-59 */
int tm_min; /* 0-59 */
int tm_hour; /* 0-23 */
int tm_mday; /* 1-31 */
int tm_mon; /* 0-11 */
int tm_year; /* n+1900 */
int tm_wday; /* (sun)0-6*/
int tm_yday; /* 0-366 */
int tm_isdst; /* is daylight savings? */
/* (the is daylight flag is not implemented by DICE) */
};
INPUTS
time_t *t; pointer to a time_t
RESULTS
struct tm *tp; pointer to a struct tm structure filled out
according to the passed time.
SEE ALSO
time, asctime, strftime, ctime, clock
EXAMPLE
/*
* Note that it is much easier to format time/date
* strings with strftime().
*/
#include <stdio.h>
#include <time.h>
main()
{
time_t t = time(NULL);
struct tm *tp = localtime(&t);
printf("The time is %02d:%02d:%02d\n", tp->tm_hour,
tp->tm_min, tp->tm_sec);
return(0);
}
dice/LockAddr,LockAddrB,TryLockAddr,TryLockAddrB,UnlockAddr,UnlockAddrB
FUNCTION
LockAddr: Gain Exclusive, Fast semaphore (bit 0)
LockAddrB: Gain Exclusive, Fast semaphore (bit n 0-7)
TryLockAddr: Non- Blocking version of LockAddr
TryLockAddrB: Non-Blocking version of LockAddrB
UnlockAddr: Release exclusive semaphore, bit 0
UnlockAddrB: Release exclusive semaphore, bit n 0-7 (DICE)
SYNTAX
void LockAddr(lck);
void LockAddrB(bitno, lck);
int r = TryLockAddr(lck);
int r = TryLockAddrB(bitno, lck);
void UnlockAddr(lck);
void UnlockAddrB(bitno, lck);
long lck[2];
DESCRIPTION
These are custom DICE functions used for inter-task locking
semaphores in programs that need such functions. These routines are
somewhat faster than standard Amiga semaphore routines and take less
memory, though at the cost of DICE specific. To use an inter-task
lock one first initializes an lck array to 0's. The entry long
lck[2]; is an array of two longwords that the lock routines will use
to do their stuff. This array should be zero'd only once at program
initialization time (the master task before any other tasks are
created that use it). Each lck array may hold up to 8 locks, hence
the LockAddrB calls. The non-B calls use lock #0 for simplicity. For
simplicity we will only discuss non-B calls.
To gain a lock you may call LockAddr with the address of the lck
array (which, being an array, does not need the & in the call). This
routine will not return until the lock can be obtained. You may also
use TryLockAddr to attempt to gain a lock. The return value is: -1
if the command is unable to obtain the lock (that is, it is in use),
1 if the lock has been obtained. To release an obtained lock you
call UnlockAddr(lck).
## WARNING: DO NOT RELEASE A LOCK YOU DO NOT HAVE!
INPUTS
long *lck; a pointer to two longwords, initially zero'd
-int bitno; lock # ... up to 8 independant locks exist for
each lck structure
RESULTS
int r; (TryLock only), -1 on failure, 1 on success.
EXAMPLE
/*
* This program obtains a lock based at a public
* message port and holds it for ten seconds before
* releasing it. The public message port is left
* in memory (but only exists once no matter how
* many programs you run).
*
* To test locking, open up two or more CLI's and run
* the program simultaniously (or as close as your
* fingers can make it) two or more times. Only one
* program will 'have' the lock at a time.
*
* we use AllocMem() so the port survives the program
*/
#include <exec/types.h>
#include <exec/ports.h>
#include <exec/memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct
{
struct MsgPort Port;
long Lock[2];
}
MyPort;
extern void *FindPort();
extern void *CreatePort();
extern void *AllocMem();
MyPort *Port;
short HaveLock;
int brk()
{
if (HaveLock)
UnlockAddr(Port->Lock);
return(1); /* abort */
}
main()
{
char *portName = "Lock-Test";
onbreak(brk);
Forbid();
if ((Port = FindPort(portName)) == NULL)
{
MyPort *port;
port = AllocMem(sizeof(MyPort) + strlen(portName)
+ 1, MEMF_PUBLIC | MEMF_CLEAR);
assert(port);
port->Port.mp_Node.ln_Name = (char *)(port + 1);
port->Port.mp_Node.ln_Type = NT_MSGPORT;
strcpy(port->Port.mp_Node.ln_Name, portName);
AddPort(port);
Port = port;
}
Permit();
puts("getting lock");
LockAddr(Port->Lock);
HaveLock = 1;
puts("Got the lock!, sleeping for 10 seconds");
sleep(10);
UnlockAddr(Port->Lock);
HaveLock = 0;
puts("released lock");
return(0);
}
dice/log,flog dice/log,flog
FUNCTION
log: return the log of a double, base e (ANSI)
flog: return the log a float, base e (ANSI)
LIBRARY
m.lib
SYNTAX
#include <math.h>
double a = log(b);
double b;
float c = flog(d);
float d;
DESCRIPTION
The former command returns the log of the double quantity, base e;
the latter returns the log of the float quantity, base e.
INPUTS
double b; double floating point value float d; float
floating point value
RESULTS
double a; result double floating point value float c;
result float floating point value
SEE ALSO
acos, asin, atan, cos, exp, fabs, log10, pow, sin, sqrt, tan facos,
fasin
dice/log10,flog10 dice/log10,flog10
FUNCTION
log10: return the logarithm of a double, base 10 (ANSI)
flog10: return the logarithm of a float, base 10 (ANSI)
LIBRARY
m.lib
SYNTAX
#include <math.h>
double a = log10(b);
double b;
float c = flog10(d);
float d;
DESCRIPTION
log10 returns the log of a double quantity, base 10; flog10 returns
the log of the floating point quantity, base 10.
INPUTS
double b; double floating point value
float d; float floating point value
RESULTS
double a; result double floating point value
float c; result float floating point value
SEE ALSO
acos, asin, atan, cos, exp, fabs, log, pow, sin, sqrt, tan facos,
fasin
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = log10(0.25);
printf("log10 0.25 = %lf\n", a); /* -0.6021 */
}
{ /* less accuracy */
float a = flog10(0.25);
printf("log10 0.25 = %lf\n", (double)a);
}
return(0);
}
dice/lseek dice/lseek
FUNCTION
seek within a file descriptor (UNIX)
SYNTAX
#include <fcntl.h>
long newpos = lseek(fd, offset, how)
int fd;
long offset;
int how;
DESCRIPTION
lseek changes where the file descriptor points to within the open
file. You may specify an offset relative to the beginning of the
file, the current position in the file, or the end of the file:
Val : Purpose
====+=========================================================
0 : absolute offset (relative to the beginning of the file)
----+---------------------------------------------------------
1 : offset relative to the current position in the file
----+---------------------------------------------------------
2 : offset relative to the end of the file
----+---------------------------------------------------------
Negative offsets may be specified when relative modes are used. The
function lseek returns the new position in the file relative to the
beginning of the file (i.e. an absolute offset).
|| NOTE: offsets are relative. So, for example, if you want to seek
|| to the fourth character from the end of the file you would
|| lseek(fd, -4L, 2);. Refer to the file_descriptor manual page for
|| general information. Unlike file pointers and file handles, the
|| file descriptor is checked for validity and will simply return an
|| error if illegal.
INPUTS
int fd; file descriptor
long offset; offset relative to how
int how; 0 = rel beginning, 1 = rel middle, 2 = rel end
RESULTS
int newpos; new position in file (absolute) or < 0 if error
SEE ALSO
close, creat, fcntl, fdtofh, getfh, ioctl, isatty, mkdir, open, read,
rmdir, unlink, write
EXAMPLE
See open for an example.
dice/main dice/main
FUNCTION
main program entry (ANSI)
SYNTAX
#include <anything.h>
int main(int argc, char **argv)
{
/* your pride and joy goes here */
}
DESCRIPTION
The main routine is the entry point called after normal
initialization of c.lib and the program enviroment is done by the
startup module (c.o) and _main routine (in c.lib). Under ANSI C main
is expected to return an integer exit code. You can no longer simply
fall through without returning any value. Returning an exit code
from your main routine is exactly the same as exiting with it.
|| NOTE: Any program run from the WORKBENCH uses a different access
|| point. Specifically, a program run from the WORKBENCH will run
|| wbmain instead of main. Please refer to the manual page for
|| wbmain for WORKBENCH operation.
If you do not supply a wbmain a dummy wbmain will be supplied by the
library which simply exits out of the program.
INPUTS
int argc; number of arguments
char *argv; array pointer to arguments
SEE ALSO
wbmain, _main, exit, _exit
EXAMPLE
/* Print back out all given arguments */
#include <stdio.h>
int main(int ac, char**av)
{
int i;
for (i = 0; i < ac; ++i) {
printf("Arg #%d = %s\n", i, av[i]);
}
return(0);
}
dice/_main dice/_main
FUNCTION
main program entry, bypass standard c.lib initialization (DICE)
SYNTAX
#include <the_world.h>
void _main(int arglen, char *argptr)
{
/* your very special code goes here */
}
DESCRIPTION
The _main entry point is called by the startup module (c.o).
Normally _main is part of c.lib and does stdio and other
initialization before calling the user main routine. _main is
responsible for opening the stderr channel as well. However, if you
specify your own _main you will overide the c.lib version. Normally
you either fall through or _exit from _main. A programmable can use
the _main entry point when the executable uses nothing but system
library routines. That is, you make no calls to stdio functions such
as puts, printf, etc., to low level IO routines such as open, close,
read, etc., or malloc or any routine that uses malloc. Self contained
routines such as strcpy may still be called, and, of course, you may
open any libraries you wish and make library calls. Since the
auto-library openning and closing is done by the startup module
(c.o), "dos.library" will still be opened for you automatically if
you make any DOS calls.
Using the _main entry point usually results in a substantially
smaller executable because stdio and other library routines
referenced by the c.lib. _main and exit are never referenced and thus
never become part of the executable. It is NOT SUGGESTED that
beginning C programmers use the _main entry point.
|| NOTE: _main is called by the startup module whether the program
|| was run from the CLI or the WORKBENCH. You must detect which
|| yourself and also deal with the WORKBENCH message yourself.
int argc; number of arguments
char *argv; array pointer to arguments
SEE ALSO
_exit, main, exit
EXAMPLE
/*
** This program comes in at under 600 bytes.
*/
_main()
{
Write(Output(), "UG!\n", 4);
_exit(0);
}
dice/malloc dice/malloc
FUNCTION
allocate memory, the memory is NOT automatically cleared (ANSI)
SYNTAX
#include <stdlib.h>
void *ptr = malloc(bytes);
size_t bytes;
DESCRIPTION
malloc allocates the specified number of bytes of memory. The
returned pointer is longword aligned; malloc returns NULL if the
memory could not be allocated.
|| NOTE: Unlike calloc, malloc does not zero the memory before it
|| returns.
INPUTS
size_t bytes; number of bytes to allocate
RESULTS
void *ptr; pointer to base of allocated memory. The memory
is not zero'd.
SEE ALSO
calloc, strdup
dice/memcmp dice/memcmp
FUNCTION
compare two memory buffers (ANSI)
SYNTAX
#include <string.h>
int r = memcmp(s1, s2, bytes)
void *s1;
void *s2;
size_t bytes;
DESCRIPTION
memcmp compares two memory buffers. A byte by byte unsigned
comparison is done. When a comparison fails and the byte in s1 is
less than the byte in s2 then -1 is returned. If the byte in s1 is
greater than the byte in s2 then 1 is returned. If the count is
exhausted and all comparisons succeed then 0 is returned indicating
the two buffers are the same.
INPUTS
void *s1; pointer to first buffer
void *s2; pointer to second buffer
size_t bytes; size of each buffer
RESULTS
int r; -1 if buf s1 < buf s2, 0 if buf s1 == buf s2, 1
if buf s1 > buf s2.
SEE ALSO
memset, setmem, bzero, clrmem, bcopy, bcmp, movmem, memcpy, memmove
EXAMPLE
#include <stdlib.h>
#include <assert.h>
main()
{
unsigned char buf1[5] = {9, 10, 1, 12}; /* 1,729 */
unsigned char buf2[5] = {9, 10, 1, 12}; /* 1,729 */
int r;
r = memcmp(buf1, buf2, 4);
assert(r == 0);
buf1[2] = 0;
r = memcmp(buf1, buf2, 4);
assert(r < 0);
buf1[2] = 42;
r = memcmp(buf1, buf2, 4);
assert(r > 0);
return(0);
}
dice/memcpy,memmove,movmem,bcopy dice/memcpy,memmove,movmem,bcopy
FUNCTION
memcopy: copy memory, ANSI, overlapped memory buffers illegal
memmov: copy memory, ANSI, works with overlapped memory buffers
movmem: copy memory, UNIX, works with overlapped memory buffers
bcopy: copy memory, UNIX, works with overlapped memory buffers
SYNTAX
#include <string.h>
void *ptr = memcpy(d, s, bytes);
void *ptr = memmove(d, s, bytes);
void *ptr = movmem(s, d, bytes);
void *ptr = bcopy(s, d, bytes);
void *d;
void *s;
size_t bytes;
DESCRIPTION
These functions copy memory from one region to another. Unlike
string routines these functions do not stop the copy when a NULL is
encountered.
## WARNING: Be careful about argument ordering. Some calls take the
## source buffer first and other calls take the destination buffer
## first.
The ANSI committee opted for a destination, source ordering rather
than the more logical source, destination ordering. Thus, many
programmers will use the non-standard movmem call instead of the ANSI
memmove call. The ANSI function 'memcpy' as defined by the ANSI
standard cannot handle overlapped memory areas. The Amiga
implementation can but you should remember this if you intend to port
your code.
|| NOTE: DICE's memory move optimizes the copy using movem when
|| possible, yielding very fast memory copies for large buffers. The
|| UNIX bcopy call exists for compatibility purposes and should not
|| be used with new programs.
INPUTS
void *s; source buffer
void *d; destination buffer
RESULTS
void *ptr; pointer to the destination buffer(d)
SEE ALSO
memset, setmem, bzero, clrmem, cmpmem, memcmp
EXAMPLE
/*
* This example copies the entire buffer, not just
* the part containing the string. Normally one just
* uses string routines.
*/
#include <string.h>
#include <assert.h>
main()
{
char s[16];
char d[16];
void *p;
strcpy(s, "This is a test");
p = movmem(s, d, sizeof(s));
assert(p == d);
puts(d);
strcpy(s, "Googolplex");
p = bcopy(s, d, sizeof(s));
assert(p == d);
puts(d);
strcpy(s, "EchoBeko");
p = memcpy(d, s, sizeof(s));
assert(p == d);
puts(d);
strcpy(s, "GakFuBar");
p = memmove(d, s, sizeof(s));
assert(p == d);
puts(d);
return(0);
}
dice/memset,setmem,clrmem,bzero dice/memset,setmem,clrmem,bzero
FUNCTION
memset: ANSI, set memory buffer to a byte value
setmem: UNIX, set memory buffer to a byte value
clrmem: DICE, zero out a memory buffer
bzero: UNIX, zero out a memory buffer
SYNTAX
#include <string.h>
void *ptr = memset(buf, c, n);
void *ptr = setmem(buf, n, c);
void *ptr = clrmem(buf, n);
void *ptr = bzero(buf, n);
void *buf;
int c;
size_t n;
DESCRIPTION
These functions fill a memory buffer with the specified character c.
C is converted to an unsigned chararacter by the fill routine before
beginning the fill. N bytes are filled.
## WARNING: Again, watch out for argument ordering, especially for
## the ANSI memset call.
The ANSI committee chose bizarre call ordering so there is another
defacto standard call called setmem. The function bzero exists for
UNIX compatibility, and clrmem is yet another call (this time
introduced by DICE--sorry!). memset and setmem are the most portable
calls.
INPUTS
void *buf; pointer to buffer to fill
int c; character to copy into buffer
(setmem, memset) size_t n;
# of bytes to fill
RESULTS
void *ptr; pointer to buffer (== buf).
SEE ALSO
malloc, calloc, strdup, movmem, cmpmem
EXAMPLE
#include <string.h>
#include <assert.h>
#include <stdlib.h>
main()
{
char buf[32];
char *b;
b = setmem(buf, 32, 0);
assert(b == buf);
b = setmem(buf, 4, 'a');
b = memset(buf + 4, 'b' , 4);
puts(buf); /* aaaabbbb */
return(0);
}
dice/mkdir dice/mkdir
FUNCTION
create a directory (UNIX)
SYNTAX
#include <stdio.h>
int error = mkdir(dirname)
char *dirname;
DESCRIPTION
mkdir creates a new directory. It returns 0 if successful, -1 if not
(with errno set to an error code).
INPUTS
char *dirname; filename of directory to create
RESULTS
int r; 0 if no error, < 0 if error
SEE ALSO
close, creat, fcntl, fdtofh, getfh, ioctl, isatty, lseek, mkdir,
open, read, rmdir, unlink, write
EXAMPLE
main()
{
int r;
r = mkdir("T:tmpdir");
if (r == 0)
puts("Created T:tmpdir successfully");
else
puts("Unable to create directory T:tmpdir");
}
dice/_mods,_modu dice/_mods,_modu
FUNCTION
signed/unsigned long modulus 32 (DICE)
DESCRIPTION
These are assembly functions that DICE uses whenever it needs to do a
long modulus. The functions are not callable from C.
INPUTS
D0 32 bit signed/unsigned integer
D1 32 bit signed/unsigned integer
RESULTS
D0 Remainder of D0 divided by D1
SEE ALSO
_divs, _divu, _muls, _mulu
dice/_muls,_mulu dice/_muls,_mulu
FUNCTION
signed/unsigned long multiply (DICE)
DESCRIPTION
These are assembly functions that DICE uses whenever it needs to do
long multiplication. They are not callable from C.
INPUTS
D0 32 bit signed/unsigned integer
D1 32 bit signed/unsigned integer
RESULTS
D0 D0 multiplied by D1
SEE ALSO
_divs, _divu, _mods, _modu
dice/onbreak dice/onbreak
FUNCTION
Set special ^C handler (AmigaDOS)
SYNTAX
typedef int (*fptr)();
fptr oldfunc = onbreak(newfunc);
fptr newfunc;
DESCRIPTION
onbreak sets a special function to handle ^C. It takes a pointer to
this function and returns a pointer to the previous onbreak function,
if any. When ^C is hit, the special onbreak function is called
before any other action. If the onbreak function returns a non-zero
value, ^C aborts the program like it usually does. If the function
returns 0, however, the ^C is completely ignored.
INPUTS
newfunc pointer to function or NULL
RESULTS
fptr oldfunc; pointer to previous onbreak function
SEE ALSO
atexit
EXAMPLE
/*
* Note: The reentrancy check is needed because of both
* the puts and the sleep() call.
*/
#include <stdio.h>
#include <stdlib.h>
int brk()
{
static short cnt = 0; /* check for reentrancy */
if (cnt) /* if not 0 then reentered! */
return(0);
++cnt;
puts("Nah Nah, you can't break me!");
sleep(1);
--cnt;
return(0);
}
int main()
{
short i;
onbreak(brk);
puts("Hit ^C while I loop from 1 to 100.");
sleep(2);
for (i = 1; i <= 100; ++i)
printf("Loop, counting, count = %d\n", i);
return(0);
}
dice/open dice/open
FUNCTION
open a file (UNIX)
SYNTAX
#include <fcntl.h>
int fd = open(name, modes);
char *name;
int modes;
DESCRIPTION
open opens a file of the specified name using the specified modes.
The combinations yield different results as described below:
O_RDONLY : open file for reading only
----------+-----------------------------------------------------------------
O_WRONLY : open file for writing only
----------+-----------------------------------------------------------------
O_RDWR : open file for reading and writing
----------+-----------------------------------------------------------------
O_NDELAY : open file non-blocking (not implemented)
----------+-----------------------------------------------------------------
O_APPEND : open file for writing only and force all writes to append to
: the file regardless of the current seek position. open is a
: lower-level construct than the more standard fopen.
----------+-----------------------------------------------------------------
O_CREAT creates the file if it does not exist; O_TRUNC truncates the
file if it does exist; O_EXCL is used only with O_CREAT and if the
file already exists the open will fail; O_BINARY opens the file for
binary reading and writing, vs text. This flag is ignored by DICE
since there is no difference on the Amiga. However, on Messy-DOS
systems, CR-LF must be converted to an LF when reading text files.
open returns a descriptor (>= 0) or error (< 0) on failure.
|| NOTE: Refer to the file_descriptor manual page for general
|| information. Unlike file pointers and file handles, the file
|| descriptor is checked for validity and will simply return an error
|| if illegal.
INPUTS
char *name; filename to open
long modes; modes to open the file with
RESULTS
int fd; A file descriptor if >= 0, an error if < 0.
SEE ALSO
close, creat, fcntl, fdtofh, fopen, ioctl, isatty, lseek, mkdir,
read, rmdir, unlink, write
EXAMPLE
#include <fcntl.h>
#include <assert.h>
main()
{
int fd, r;
fd = open("T:xx", O_WRONLY|O_CREAT|O_TRUNC);
assert(fd >= 0);
close(fd);
fd = open("T:xx", O_CREAT|O_EXCL|O_TRUNC|O_WRONLY);
assert(fd < 0); /* will fail, file already exists */
remove("T:xx");
fd = open("T:xx", O_CREAT|O_TRUNC|O_WRONLY);
assert(fd >= 0); /* will work */
write(fd, "FuBar-", 6);
lseek(fd, 0L, 0); /* seek back to start of file */
r = write(fd, "XxXxx", 5);
assert(r == 5);
close(fd);
fd = open("T:xx", O_APPEND|O_WRONLY);
assert(fd >= 0);
write(fd, "FuBar\n", 6);
close(fd);
printf("type t:xx should return \"XxXXX-FuBar\"\n");
return(0);
}
dice/perror dice/perror
FUNCTION
output error message associated with errno and text to stderr (ANSI)
SYNTAX
#include <stdio.h>
void perror(str);
const char *str;
DESCRIPTION
perror outputs the specified string, a colon, and the error number
and error message associated with the current value of errno to
stderr, ending with a newline. Using perror is a common way to
generate error messages due to IO failures.
INPUTS
char *str; string message to include in error output
EXAMPLE
#include <stdio.h>
main()
{
FILE *fp = fopen("T:DoesNotExist", "r");
if( fp ) {
puts("T:DoesNotExist is not supposed to exist!");
exit(1);
}
perror("fopen");
return(0);
}
dice/pow,fpow dice/pow,fpow
FUNCTION
pow: return one double to the power of another (ANSI)
fpow: return one float to the power of another (ANSI)
LIBRARY
m.lib
SYNTAX
#include <math.h>
double a = pow(b, bp);
double bp;
double b;
float c = flog(d, dp);
float dp; float d;
DESCRIPTION
pow returns one double to the power of another; fpow returns one
float to the power of another.
INPUTS
double b; double floating point value (base)
double bp; double floating point value (exponent)
float d; float floating point value (base)
float dp; float floating point value (exponent)
RESULTS
double a; double floating point value
float c; float floating point value
SEE ALSO
acos, asin, atan, cos, exp, fabs, log, log10, pow, sin, sqrt, tan
facos, fasin
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = pow(0.25, 4.0);
printf("pow 0.25 ^^ 4.0 = %lf\n", a);
/* 0.0039 */
}
{ /* less accuracy */
float a = fpow(0.25, 4.0);
printf("pow 0.25 ^^ 4.0 = %lf\n", (double)a);
}
return(0);
}
dice/printf,fprintf,sprintf,vprintf,vfprintf,vsprintf
FUNCTION
formatted output to stdout, file pointer, or buffer (ANSI)
SYNTAX
#include <stdio.h>
#include <stdarg.h> /* for v[f/s]printf() only */
int n = printf(fmt, ...);
int n = fprintf(fp, fmt, ...);
int n = sprintf(buf, fmt, ...);
int n = vprintf(fmt, argvect);
int n = vfprintf(fp, fmt, argvect);
int n = vsprintf(buf, fmt, argvect);
FILE *fp;
char *fmt;
char *buf;
va_list argvect;
DESCRIPTION
These functions offer formatted printing in various flavors. printf
and vprintf output to stdout; fprintf and vfprintf output to a file
pointer (fp); sprintf and vsprintf output to a character buffer. All
routines return the number of characters written if successful, a
negative number if not. Only sprintf and vsprintf are limited in
terms of output size (it cannot exceed the buffer you give it). The
common argument to all routines is the format specifier. The format
specifier is scanned to determine how to handle the arguments to the
call (or the argument list for vfprintf/vsprintf). Characters are
copied to the output until a % is encountered. %% indicates a literal
'%' character. Otherwise, the % is followed by a control sequence
that tells printf how to output the corresponding argument. The
quantity is output and the scan continues until the end of the format
string. The % formats are interpreted as follows:
%[flags][#[.#]][modifier]<conversion-specifier>
Items in brackets are optional. After the %, zero or more flags may
be specified. Then, an optional integer which represents the minimum
field width for the object may also be specified. If an integer is
specified it may be followed by a period and another integer that
represents that precision with which a number is printed. Zero or
more modifiers may then be specified followed by a mandatory
conversion specifier.
Either or both integers (#[.#]) may be specified as a '*', as in
"%*d", specifying that the minimum field width and/or precision is
specified as an integer in the argument that occurs before the
conversion object. For example, printf("--%*d--\n", 10, 23); would
print the number 23 right justified in a field 10 characters wide.
FLAGS
-----
Minus (-) Left justify text within the field.
<space> This flag places a blank in front of positive signed numbers, and
a minus in front of negative numbers. This option allows columns
of positive and negative numbers to line up.
Plus (+) Cuase a plus sign to be placed before a positive result. A minus
sign is always placed before a negative result.
Pound (#) Format output acording to the type of input. e, E, f, F always
retains the decimal point. g, G always retains the decimal
point, and trailing zeros are kept. x and X print '0x' and '0X'
respectively before the number (except that this is not currently
implemented by DICE).
0 Pad columns with zeros instead of spaces. Ignored if a precision
is specified or if the '-' flag is specified.
MODIFIERS
---------
h Indicates the corresponding integer argument is a short or an
unsigned short (stands for "half-size"). Affects scanf(), but
since DIEC uses 32 bit integers, has no effect on printf().
l Indicates the corresponding integer argument is a long or
unsigned long. Also indicates floating point argument is a
double (else is a float). Under DICE this flag is superfluous for
integers, but for portability reasons you want to specify it when
an argument is explicitly a long.
CONVERSION SPECIFIER
--------------------
c Output integer as a character.
d Output a signed integer.
e Output a double quantity in exponential form. The precision
specifies the number of digits beyond the decimal point to print,
ie: [-]d.dddddde+/-dd.
E Upper case version of e.
f Output a double quantity. The precision specifies the number of
digits beyond the decimal point to print, ie: [-]d.dddddd
g Output a double quantity using either the 'e' or 'f' form,
depending on the exponent.
G Output a double quantity using either the 'E' or 'f' form,
depending on the exponent.
i Same as 'd', but less portable.
n The argument is a pointer to an integer which is used to set the
integer to the bytes written out so far. This is especially
useful with sprintf todetermine where a particular part of the
format begins in the output buffer.
o The unsigned integer quantity is converted to ASCII-octal.
p The pointer is printed (basically the hexadecimal address is
printed).
s The NULL-terminated string represented by the character pointer
is printed.
u The unsigned integer quantity is converted to ASCII-decimal.
x The unsigned integer quantity is converted to ASCII-hex using
'0'-'9', 'a'-'f'.
X The unsigned integer quantity is converted to ASCII-hex using
upper case 'A'-'F' instead of lower case.
INPUTS
FILE *fp; file pointer (fprintf, vfprintf)
char *fmt; format string, e.g. "Answer is %d\n"
char *buf; buffer (sprintf, vsprintf)
va_list argvect; arg list (vprintf, vfprintf, vsprintf)
RESULTS
int n; Number of characters written if successful, a
negative number if not. For sprintf and vsprintf
the NULL character at the end of the string is
NOT included in the count.
SEE ALSO
puts, fputs, fwrite
EXAMPLE
/*
** Example using most printf conversion specifiers.
** Compile with -lm for the math functions to operate.
*/
#include <stdio.h>
#include <stdarg.h>
void test_varargs(); /* Always use function prototypes */
main()
{
char buf[256];
int n, i;
printf("Normal: ab%c %03d %03o $%p Fu%s %u $%x $%8X $%08lX\n",
'c', 43, 11, buf, "Bar",32094,4095,4095,4095 );
printf("Math: Double: %le Float: %lf Formatted Float: %2.2lf\n",
1.23E-2, 1.23E-2, 1.257 );
printf("%9s\n", "<-"); /* Specify 9 chracter field width */
printf("%*s\n", 9, "<-"); /* Indirect specification */
n = sprintf(buf, "Save %n%s", &i, "the whales");
puts(buf);
printf("String is %d+1 bytes long, with a %%n token at %d.\n", n,
i);
fprintf(stdout, "\nThis is a call to %s\n", "fprintf");
test_varargs("%d %d %d ", 1, 2, 3);
return(0);
}
void test_varargs(ctl, ...)
char *ctl;
{
va_list va;
int n;
va_start(va, ctl);
n = vprintf(ctl, va);
printf("<- %d chars written\n", n);
va_end(va);
}
dice/putchar dice/putchar
FUNCTION
output character to stdout (ANSI)
SYNTAX
#include <stdio.h>
int r = putchar(c); /* MACRO */
DESCRIPTION
putchar outputs a character to stdout, returning the output character
unless an error occured. If an error occured then EOF is returned.
|| NOTE: Refer to the file_pointer manual page for general
|| information.
INPUTS
int c; character to output, 0 to 255
RESULTS
int r; same as c unless error occured in which case EOF.
SEE ALSO
putc, fputc, fread, fwrite, getc, getchar
EXAMPLE
/*
* copy stdin to stdout using getchar/putchar. Normally
* one uses fread/fwrite, but I'll save that for the
* fread manual page. Note that I output the initial
* message to stderr so it does not get stuck into stdout
* in case the user has redirected stdout.
*
* See getc manual page for equivalent example using
* getc/putc
*/
#include <stdio.h>
main()
{
int c;
fputs("Type a couple of lines, then ^\\ (EOF)\n",
stderr);
while ((c = getchar()) != EOF)
{
putchar(c);
}
return(0);
}
dice/qsort dice/qsort
FUNCTION
sort an array of objects (ANSI)
SYNTAX
#include <stdio.h>
#include <stdlib.h>
(void) qsort(array, numElem, elemSize, compare_func)
void *array;
size_t numElem;
size_t elemSize;
int (*comp_func)(const void *arg1, const void *arg2);
DESCRIPTION
qsort sorts numElem elements in an array based at array. Each element
is elemSize bytes long. When a comparison is required, qsort calls
the passed compare_func function pointer with a pointer to the two
elements being sorted. DICE currently implements qsort with a simple
merge sort algorithm, using relatively slow movmems to avoid having
to allocate much additional storage. Very little stack is used.
Traditional qsort employs a stack based quick-sort algorithm that
might use a massive amount of stack.
INPUTS
void *array; pointer to base of array of objects
size_t numElem; number of elements in the array
size_t elemSize; size, in bytes, of each element
int (*comp_func)()
function pointer to compare function given
pointers to two of the elements
EXAMPLE
#include <stdio.h>
#include <stdlib.h>
#define NUM_GENIUS 8
char *StrList[NUM_GENIUS] =
{
"Euler", "Einstein", "Pascal", "Zeno",
"Godel", "Leibniz", "Euclid", "Von Neumann"
};
my_comp(s1, s2)
char **s1; char **s2;
{
return(strcmp(*s1, *s2));
}
main()
{
short i;
qsort(StrList, NUM_GENIUS, sizeof(char *), my_comp);
for (i = 0; i < NUM_GENIUS; ++i)
printf("%d %s\n", i, StrList[i]);
return(0);
}
dice/raise dice/raise
FUNCTION
raise a signal (cause an 'interrupt' synchronously) (ANSI)
SYNTAX
int r = raise(signo);
int signo;
DESCRIPTION
raise causes a signal to occur and the appropriate action to be
taken. It returns 0 on success, -1 if the signo is invalid (outside
the range of allowed signals). When you raise a signal, the signal
is set back to its default vector before the handler is called.
Thus, if you are allowing multiple signals to occur you MUST restore
the signal vector with signal from your signal handler before it
returns.
INPUTS
int signo; signal to cause
RESULTS
int r; 0 on success, -1 if signo is out of range.
SEE ALSO
signal
EXAMPLE
/*
* prints the numbers 0 to 99, except only gets
* to 50 because we 'cause' a ^C.
*/
#include <signal.h>
main()
{
short i;
for (i = 0; i < 100; ++i) {
printf("i = %d\n", i);
if (i == 50)
raise(SIGINT);
}
return(0);
}
dice/rand dice/rand
FUNCTION
return pseudo-random number (ANSI)
SYNTAX
#include <stdio.h>
#include <stdlib.h>
int n = rand(void);
(void) srand(seed)
unsigned int seed;
DESCRIPTION
rand returns a random number as a positive integer ranging from 0 to
RAND_MAX. RAND_MAX is defined in stdlib.h and is at least 32767.
DICE implements it as 2147483647 == 0x7FFFFFFF.
The initial seed used to generate the pseudo-random sequence is 1,
but may be reinitialized to any number you desire using srand. rand
is guaranteed to return the same sequence for the same seed.
INPUTS
none
RESULTS
int n; returned by rand(), this number will be a
positive integer.
SEE ALSO
srand
EXAMPLE
#include <stdio.h>
#include <stdlib.h>
main(int ac, char**av)
{
short i;
short j;
if (ac == 2) {
int seed =
strtol(av[1], NULL, 0);
srand(seed);
printf("using seed = %d\n",
seed);
}
else
puts("using seed = 1");
for (i = 0; i < 10; ++i) {
int n = rand();
printf("Random number: %08lx\t(%d)\n", n, n);
}
for (i = 0; i < 31; ++i) {
int isone = 0;
long mask = 1 << i;
for (j = 0; j < 32767; ++j) {
if (rand() & mask) ++isone;
}
printf("bit %d %5d:%-5d (deviation %d)\n", i,
32767 - isone, isone, 16384 -isone);
}
return(0);
}
dice/read dice/read
FUNCTION
read data from a file (UNIX)
SYNTAX
#include <fcntl.h>
int r = read(fd, buf, bytes);
int fd;
void *buf;
int bytes;
DESCRIPTION
read reads data from a file starting at the current seek position.
read returns the number of bytes read or -1 if a read error occurs.
With normal files, read will always return the number of bytes
requested until the end of file is reached, in which case read may
return fewer than the number of bytes requested. If at the end of a
file, read will return 0. With devices read may or may not return the
number of bytes requested depending on the device.
|| NOTE: Refer to the file_descriptor manual page for general
|| information Unlike file pointers and file handles, the file
|| descriptor is checked for validity and will simply return an error
|| if illegal.
INPUTS
int fd; file descriptor to read from
void *buf; pointer to buffer to read data into
int len; maximum number of bytes to read
RESULTS
int r; number of bytes actually read (could be less than
len or 0), or < 0 if error.
SEE ALSO
close, creat, fcntl, fdtofh, ioctl, isatty, lseek, mkdir, open, read,
rmdir, unlink, write
EXAMPLE
#include <fcntl.h>
#include <assert.h>
main()
{
int fd;
int r;
char buf[32];
fd = open("T:xx", O_WRONLY|O_CREAT|O_TRUNC);
assert(fd >= 0);
write(fd, "FuBar\n", 6);
close(fd);
fd = open("T:xx", O_RDONLY);
assert(fd >= 0);
r = read(fd, buf, sizeof(buf)); /* sizeof(buf)==32 */
close(fd);
assert(r == 6);
/*
* note that the buffer is not terminated with
* a NULL, but since we are using write() which
* requires a length it does not matter
*/
write(1, buf, r);
}
dice/realloc dice/realloc
FUNCTION
reallocate memory allocated by calloc, malloc, or strdup (ANSI)
SYNTAX
#include <stdlib.h>
void *newptr = realloc(oldptr, bytes)
void *oldptr;
size_t bytes;
DESCRIPTION
realloc reallocates a previously allocated buffer, making it larger
or smaller. It returns a pointer to a new buffer which might be the
same as the old buffer, but might not. Data in the original buffer
is copied to the new buffer and the original buffer is freed. When
extending a buffer with realloc note that the extended bytes (beyond
the original buffer) will come up garbage. You may pass a NULL as
the first argument to realloc which basically makes realloc a malloc.
INPUTS
void *oldptr; pointer to original allocated buffer
size_t bytes; size of new buffer
RESULTS
void *newptr; pointer to new buffer
SEE ALSO
malloc, calloc, strdup
EXAMPLE
#include <string.h>
#include <assert.h>
#include <stdlib.h>
main()
{
char *s;
int len;
s = strdup("This is a test");
assert(s);
len = strlen(s);
/*
* Remember that len does not include the NULL
* byte at the end of the string
*/
s = realloc(s, len + 8); /* make more room */
assert(s);
/*
* we can use strcat since in extending the
* allocated string the NULL *was* copied along
* with the string during the realloc.
*/
strcat(s, "xx");
puts(s); /* This is a testxx */
return(0);
}
dice/rega4 dice/rega4
FUNCTION
return current contents of register A4 (DICE)
SYNTAX
char *basePtr = rega4();
DESCRIPTION
rega4 is not geta4; rega4 simply returns the current contents of the
A4 register when you need it. Note that DICE offsets the A4 register
32766 from the actual small-data base so as to be able to use the
entire -32768 to 32767 range to access 64 kilobytes of small-data.
Note that a rega4 call inside a subroutine qualified with __geta4 is
guaranteed to return the data base pointer. Also, a rega4 call from
any subroutine not called from an interrupt or a call back will
return the proper data base pointer.
## WARNING: Programs which use this function will not be able to be
## made resident.
dice/remove dice/remove
FUNCTION
delete a file (ANSI)
SYNTAX
#include <stdio.h>
int error = remove(filename);
const char *filename;
DESCRIPTION
remove deletes the specified file path returning 0 on success, a
negative number on failure. On the Amiga, an error will occur if you
try to delete a file currently opened by yourself or any other
process. remove is an ANSI function. unlink does the same thing but
is a UNIX-compatible function.
INPUTS
char *filename; filename to delete
RESULTS
int error; 0 on success, a negative number on failure
SEE ALSO
unlink
EXAMPLE
#include <stdio.h>
main()
{
int error = remove("T:XXX");
if (error < 0)
{
perror("remove(\"T:XXX\") failed");
exit(1);
}
puts("T:XXX has been deleted");
return(0);
}
dice/rename dice/rename
FUNCTION
rename a file, or move a file from one directory to another on the
same filesystem (ANSI)
SYNTAX
#include <stdio.h>
int error = rename(origname, newname);
const char *origname;
const char *newname;
DESCRIPTION
rename renames a file. You may also use rename to move a file (and
rename at the same time) to another directory on the same filesystem.
rename returns 0 on success, a negative number on failure.
INPUTS
const char *origname;
existing file const char
*newname; new filename and/or path
RESULTS
int error; 0 on success, a negative number on failure
SEE ALSO
rewind
EXAMPLE
/*
* create the file T:xxjunk and the directory
* T:junkdir then move T:xxjunk into T:junkdir
* and rename to T:yyjunk at the same time.
* As is aptly demonstrated by this example, some
* errors are not really errors. For example,
* mkdir where the dir already exists is not usually
* an error.
*/
#include <stdio.h>
#include <assert.h>
#include <errno.h>
main()
{
FILE *fp; int error;
error = mkdir("T:junkdir");
if (error < 0 && errno != EEXIST)
perror("mkdir");
fp = fopen("T:xxjunk", "w");
if (fp == NULL) {
perror("fopen"); exit(1);
}
fprintf(fp, "This was originally T:xxjunk!\n");
fclose(fp);
error = rename("T:xxjunk", "T:junkdir/yyjunk");
if (error < 0)
perror("Error renaming T:xxjunk");
else
puts("rename succeeded, look in T:junkdir");
return(0);
}
dice/rewind dice/rewind
FUNCTION
seek filepointer to beginning of file (ANSI)
SYNTAX
#include <stdio.h>
void rewind(fp);
FILE *fp;
DESCRIPTION
rewind rewinds the file to the beginning, equivalent to fseek(fp, 0L,
0);.
|| NOTE: Refer to the file_pointer manual page for general
|| information.
INPUTS
FILE *fp; file pointer to rewind
SEE ALSO
fseek, fgetpos, fsetpos
EXAMPLE
/* print a file 3 times */
#include <stdio.h>
main(int ac, char**av) {
FILE *fp;
int i;
char buf[256];
if (ac == 1) {
puts("Expected textfile argument");
exit(1);
}
fp = fopen(av[1], "r");
if (fp == NULL) {
printf("Unable to open %s\n", av[1]);
exit(1);
}
for (i = 1; i <= 3; ++i) {
rewind(fp); printf("PRINTING #%d\n", i);
while (fgets(buf, sizeof(buf), fp))
fputs(buf, stdout);
}
return(0);
}
dice/rmdir dice/rmdir
FUNCTION
delete a directory (UNIX)
SYNTAX
#include <stdio.h>
int r = rmdir(dirname);
char *dirname;
DESCRIPTION
rmdir deletes a directory. The directory must be empty for the
deletion to work. On the Amiga this call is equivalent to remove or
unlink.
INPUTS
char *dirname; name of directory to delete
RESULTS
int r; 0 if successful, non-zero if error
SEE ALSO
mkdir
EXAMPLE
#include <assert.h>
main()
{
int r;
r = mkdir("T:tmpdir");
assert(r == 0);
r = rmdir("T:tmpdir");
assert(r == 0);
}
dice/scanf,fscanf,sscanf dice/scanf,fscanf,sscanf
FUNCTION
scan formatted text and convert to variables (ANSI)
SYNTAX
#include <stdio.h>
int n = scanf(ctl, ...); /* Input: standard in */
int n = fscanf(fp, ctl, ...); /* Input: file pointer */
int n = sscanf(str,ctl, ...); /* Input: string buffer */
const char *ctl;
FILE *fp;
char *str;
DESCRIPTION
These functions scan the specified input file or buffer for fields
matching those specified by the control field. Commands starting with
% relate the scanned text to a list of pointers. The values the
pointers point to are updated (say that three times fast). Other
characters in the control field must match the scanned text exactly,
except for white space charaters, which match any length of white
space in the scanned text.
Control Field Commands
----------------------
The control field command format is as follows:
%[*][nnn][h/l/L]<conversion-specifier>
% All conversion specifiers start with %. Use %% to match a single
% in the source text.
* An optional * tells scanf to perform the conversion, but discard
the result. Do not include a destination pointer for skiped
conversions.
nnn An optional decimal number is used for string conversion to
specify a maximum field width.
h The modifier h specifies the destination should be treated as a
short integer rather, than an integer. The h conversion applies
to d, i, n, o, u, x and X.
l The modifier l specifies the destination should be treated as a
long integer, rather than an integer. The l conversion applies
to d, i, o, u, x and X.
L When used with formats e, f or g, specifies the destination
should be treated to a long double rather than a double.
Conversion Specifiers
---------------------
c With no field width specified, converts one character. With a
field width, converts the number of characters specified by the
field width into an array. The expected argument is a pointer to
a character or array of characters. No white space is skipped.
d Converts a decimal (base 10) number. The expected argument is a
pointer to an integer. The l and h modifiers may be used to
specify either a long or short integer result.
e/f/g Scans a floating point number. If the l modifier is used, a long
double pointer is expected (not implemented in DICE yet), else a
double is expected.
i Converts a number to an integer. The format should be equivalent
to that expected by strtol with a base argument of 0 (automatic
detection of format).
n This command does not scan any text. It places into an integer
the current count of processed characters.
o An octal number is expected. The value is stored to an integer.
p A pointer is expected, in the same format as the %p from printf.
The value is stored into a pointer, passed as void ** (a pointer
to any type of pointer).
s Reads a string of non-white space characters and copies into the
array specified by the argument. The argument must be of type
char * and have enough space to handle any possible string plus a
NULL terminator.
x A hexadecimal (base 16) number is expected. The value is stored
into an integer. This is equivalent to calling strtol with a
base of 16.
%% Match a single % in the input stream.
[...] Scan a scanset. Scan the input stream and place the characters
into a char * buffer until a character is read that does not
match the scanset. If a scan set begins with ^ (as in [^abcd])
then all characters are allowed except those specified in the
scanset. If a scanset begins as []abcd] or [^]abcd] then the ']'
character is included in the scan set and the set is terminated
by ']'.
|| Note: All scanf arguments are pointers. A common mistake is
|| to pass arguments directly; pointers are required. All
|| floating point arguments must be pointers to doubles.
INPUTS
char *ctl; format control string, containing % commands
FILE *fp; file pointer for fscanf
char *str; string pointer for sscanf
... pointers to variables ready to receive
conversions.
RESULTS
int n; Number of conversions that occured or -1 if no
conversions could be made (this usually means
EOF). The function may return less than the
number of requested conversions. This value does
not count any %* conversions.
SEE ALSO
sprintf, printf, fprintf, strtol
EXAMPLE
#include <stdio.h>
main(int ac, char**av)
{
int n, integer;
n = sscanf("Input: 132\n", "Input: %ld\n", &integer);
printf("First test: n=%d integer=%d ", n, integer);
short a[3] = {-1, -2, -3}; // Unscanned arguments are NOT
int b[3] = {-4, -5, -6}; // cleared - they retain
char buf1[11], buf2[11]; // former values!
buf1[0]=buf2[0]=buf2[10] = 0;
if (ac != 2) {
puts("Expected string to format!"); exit(1);
}
n = sscanf(av[1],"%hd %ho %hi %*d %X %n%10s %10c -%d-",
a+0,a+1,a+2, b+0,b+1,buf1,buf2,b+2);
printf("Second test: %d elements\n", n);
printf("a (shorts): %d %d %d\n", a[0], a[1], a[2]);
printf("b (ints) : %d %d %d\n", b[0], b[1], b[2]);
printf("buf1 : %s\nbuf2 : %s\n", buf1, buf2);
return(0);
}
/* scanf "100 100 0x100 200 0x300 reduce reuse recycle!"
** First test: n=1 integer=132 Second test: 6 elements
** a (shorts): 100 64 256
** b (ints) : 768 24 -6
** buf1 : reduce
** buf2 : reuse recy
*/
dice/setbuf,setvbuf dice/setbuf,setvbuf
FUNCTION
change a file pointer's buffering (ANSI)
SYNTAX
#include <stdio.h>
void setbuf(fp, buf);
error = setvbuf(fp, buf, mode, size);
FILE *fp; char *buf;
int mode; size_t size; int error;
DESCRIPTION
setbuf changes the internal buffer used by stdio. The buffer you
pass it must be BUFSIZ bytes in size. You can set a file pointer to
unbuffered by passing NULL for your buffer.
setvbuf supersedes this call and is, in general, a better function.
Type type argument must be one of _IOFBF (Fully Buffered), _IOLBF
(Line Buffered) or _IONBF (Non Buffered). For use with DICE it is
best to supply a buffer size, but a NULL buf pointer. DICE will
allocate buffers as they are needed.
## WARNING: If buffering is turned off for a file pointer
## representing a console device, the console device is set to
## unbuffered as well. If buffering is turned on for a file pointer
## representing a console device, the console device is set to
## buffered as well.
|| NOTE: Refer to the file_pointer manual page for general
|| information.
INPUTS
FILE *fp; file pointer to affect.
char *buf; buffer for use by the file pointer, or NULL.
int type; (setvbuf) type of buffering.
size_t size; (setvbuf) requested buffer size or zero.
int error; (setvbuf) error code (if size or type are
invalid).
EXAMPLE 1
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("CON:0/0/640/100/DICE Setbuf Test","w");
if(! fp )
exit( 10 );
fprintf(fp, "This will be buffered, ");
sleep(2);
setvbuf(fp, NULL, _IONBF, 0);
fprintf(fp, "yet these will print immediately ");
sleep(2);
fprintf(fp, "(we are unbuffered).");
sleep(4);
fprintf(fp, "\n");
setvbuf(fp, NULL, _IOLBF, 128);
fprintf(fp, "Now back to buffered... ");
sleep(2);
fprintf(fp, "(See - you had to wait).\n");
sleep(8);
fclose( fp );
return(0);
}
EXAMPLE 2
#include <stdio.h>
#define BUFFER_SIZE 128
main()
{
int c; char buf[256];
setvbuf(stdin, NULL, _IONBF, 0);
printf("Type a character: ");
fflush(stdout);
c = getchar();
printf("c = %d\n", c);
setvbuf(stdin, NULL, _IOLBF, BUFFER_SIZE);
printf("Type a line: ");
fflush(stdout);
fgets(buf, sizeof(buf), stdin);
printf("You said : %s\n", buf);
return(0);
}
dice/setjmp,longjmp dice/setjmp,longjmp
FUNCTION
setjmp: save procedure context for future long jump (ANSI)
longjmp: jump to a previously saved procedure context (ANSI)
SYNTAX
#include <setjmp.h>
int r = setjmp(enviro);
(void) longjmp(enviro, rval)
jmp_buf enviro;
int rval;
DESCRIPTION
First, setjmp stores the current procedure context into an
environment array whose type is jmp_buf. When called by a procedure
it saves the environment and returns 0. Then when called, longjmp
jumps to a previously saved environment causing execution to begin at
the setjmp call that saved that enviroment. Yet instead of returning
0 the 'resumed' setjmp returns a return value set by the longjmp
call. Jmp_buf is a typedef of an array, thus by passing a jmp_buf
structure we really pass the address of it. setjmp and longjmp are
fully compatible with dynamic stacks (-gs option to DCC).
:: Beginner's Note: setjmp and longjmp should be used sparingly, if
:: at all. They make code hard to understand, are rife with potential
:: for adding bugs and are considered even uglier than the C goto
:: statement.
In the example below main is still stacked when the longjmp occurs
and is thus valid. It would be illegal, for instance, to call a
subroutine which does a setjmp and RETURNS to you, then longjmp back
to that subroutine. The contents of the jmp_buf structure are private
and may not be modified by the program.
## WARNING: You can only longjmp to a previously saved enviroment
## that has not been unstacked. WARNING: setjmp saves the current
## state of the registers, but not any registers that get modified
## between the setjmp and the longjmp!
Thus, auto variables placed in registers (which is done so
automatically under DICE) may contain 'old' values after a longjmp if
they were modified after the setjmp. To prevent this such variables
must, by ANSI convention, be made volatile. The volatile qualifier
forces an auto variable to be placed on the stack instead of in a
register.
INPUTS
jmp_buf enviro; enviroment structure
int rval; return value (longjmp call)
RESULTS
(setjmp) int r; 0 when called directly, rval when enviroment
restored by a longjmp
SEE ALSO
onbreak, signal
EXAMPLE
#include <stdio.h>
#include <setjmp.h>
jmp_buf x;
int brk(void);
void breakme(void);
main()
{
int r;
onbreak(brk);
r = setjmp(x); // returns 0 when called by main
puts("\nArnie sez: I'll be back...");
if (r == 0)
for (;;)
breakme();
printf("Broke and jumped, r = %d\n", r);
return(0);
}
/* even though the onbreak call is supposed to return,
** we can longjmp out of it as well.
*/
int brk()
{
longjmp(x, 23);
}
void breakme()
{
puts("Break Me With ^C!");
}
dice/signal dice/signal
FUNCTION
set a signal vector for a signal (ANSI)
SYNTAX
#include <signal.h>
typedef void (*__sigfunc)(int);
__sigfunc oldfunc = signal(signo, newfunc)
int signo;
__sigfunc newfunc;
DESCRIPTION
signal sets a signal vector function for a given signal number as
defined in <signal.h> and returns the previously set function.
Currently only SIGINT causes any semi-asynchronous action to occur.
You may pass newfunc as your own signal function or one of:
SIG_ERR error (exit program)
SIG_DFL default (for break, normal operation)
SIG_IGN ignore signal (for break, ^C is now ignored)
when a signal occurs, the signal is set back to its default
condition before the handler is called. Thus, if you are
allowing multiple signals to occur you must restore the signal
vector with signal from your signal handler before it returns.
|| NOTE: On the Amiga, signals are not truly asynchronous. ^C is
|| detected during stdio calls only. No other signal is
|| implemented though you CAN modify any signal vector 0 to 31
|| and raise it with the raise call. Early versions of DICE,
|| including quite possibly this version, do not understand
|| complex type declarations containing procedural types. Thus,
|| you may have to get around the problem by building up a
|| complex procedural type with typedefs. Unlike onbreak, a
|| signal function returns no value.
INPUTS
int signo; signal to modify, usually SIGINT __sigfunc
newfunc; signal function or SIG_ERR, SIG_DFL, SIG_IGN
RESULTS
__sigfunc oldfunc;
previous signal function
SEE ALSO
raise
EXAMPLE
#include <signal.h>
void brkfunc(int);
main()
{
short i;
puts("The following is unbreakable");
sleep(1);
signal(SIGINT, SIG_IGN);
for (i = 0; i < 100; ++i) printf("1 %d\n", i);
puts("The following may be broken out of");
puts("with a cute message");
sleep(1);
signal(SIGINT, brkfunc);
for (i = 0; i < 100; ++i) printf("2 %d\n", i);
puts("The following may be broken out of");
sleep(1);
signal(SIGINT, SIG_DFL);
for (i = 0; i < 100; ++i) printf("3 %d\n", i);
puts("Hey! You never hit ^C! \
What kind of test is this!");
return(0);
}
void brkfunc(int signo)
{
printf("signo %d. Want cute? Get a kitten.\n", signo);
exit(1);
}
dice/sin,fsin dice/sin,fsin
FUNCTION
sin: return sine of a double quantity (ANSI)
fsin: return sine of a float quantity (ANSI)
LIBRARY
m.lib
SYNTAX
#include <math.h>
double a = sin(b);
double b;
float c = fsin(d);
float d;
DESCRIPTION
sin returns the sine of a double quantity; fsin returns the sine of a
floating point quantity. These functions use radian measure ("rad"
on your calulator).
INPUTS
double b; double floating point value
float d; float floating point value
RESULTS
double a; result double floating point value
float c; result float floating point value
SEE ALSO
acos, asin, atan, cos, exp, fabs, log, log10, pow, sqrt, tan, facos,
fasin
EXAMPLE
See cos for an example.
dice/sleep dice/sleep
FUNCTION
sleep for a period of time (UNIX)
SYNTAX
#include <stdio.h>
sleep(n);
int n;
DESCRIPTION
The sleep function waits for a period of time specified in seconds.
It can be interrupted by a ^C.
|| NOTE: The timekeeping of sleep is not very accurate. On the
|| Amiga, sleep is implemented with a loop of delay(50); calls.
INPUTS
int n; number of seconds to sleep
EXAMPLE
#include <stdio.h>
main(int ac, char**av)
{
puts("Sleeping for 10 seconds");
sleep(10);
puts("That was a good rest");
return(0);
}
dice/sqrt,fsqrt dice/sqrt,fsqrt
FUNCTION
sqrt: return the square root of a double (ANSI)
fsqrt: return the square root of a float (ANSI)
LIBRARY
m.lib
SYNTAX
#include <math.h>
double a = sqrt(b);
double b;
float c = fsqrt(d);
float d;
DESCRIPTION
sqrt returns the square root of a double quantity; fsqrt returns the
square root of a floating point quantity.
INPUTS
double b; double floating point value
float d; float floating point value
RESULTS
double a; double floating point value
float c; float floating point value
SEE ALSO
acos, asin, atan, cos, exp, fabs, log, log10, pow, sin, tan, facos,
fasin
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = sqrt(0.25);
printf("sqrt 0.25 = %lf\n", a);
/* 0.5000 */
}
{ /* less accuracy */
float a = fsqrt(0.25);
printf("sqrt 0.25 = %lf\n", (double)a);
}
return(0);
}
dice/srand dice/srand
FUNCTION
set seed for pseudo-random number (ANSI)
SYNTAX
#include <stdio.h>
#include <stdlib.h>
(void) srand(seed)
unsigned int seed;
DESCRIPTION
srand initializes the seed for function rand.
INPUTS
unsigned int seed;
an unsigned integer used to seed the
pseudo-random
number generator via srand.
SEE ALSO
rand
EXAMPLE
See the "rand" manual page for an example
dice/stack_abort dice/stack_abort
FUNCTION
exit point when dynamic stack allocation fails (DICE)
SYNTAX
void stack_abort(void)
{
/* .. your exit code .. */
abort();
}
DESCRIPTION
When dynamic stack allocation is enabled via the -gs option and such
an allocation fails, stack_abort is called. If you do not specify a
stack_abort routine, the c.lib stack_abort function will simply call
abort.
If you do specify a stack_abort routine, you have two choices: you
can exit out of the program, or you can simply return from the
subroutine which retries the allocation and calls stack_abort again
if it fails (perhaps wait a bit in hopes memory has become
available).
The program has about 2KB of stack left at the time this function is
called. Since a low memory condition exists when this function is
called you should not do anything that might require additional
allocations!
SEE ALSO
abort, exit
dice/stat dice/stat
FUNCTION
stat a file by name (UNIX)
SYNTAX
#include <sys/stat.h>
int error = stat(name, &stat_buf);
const char *name;
struct stat stat_buf;
DESCRIPTION
stat is a UNIX-compatible call that returns information pertaining to
the file represented by its name. If 0 is returned, stat succeeded
and the fields will be filled in as follows:
st_mode Flags S_IFDIR if directory, S_IFREG if regular file, S_IREAD if
readable, S_IWRITE if writable, S_IEXEC if executable.
st_size Size of the file, in bytes.
st_blksize
Always returns 512 (for now).
st_blocks A guess at the number of actual blocks the file takes up,
including headers and side sectors.
st_ctime Time the file was last modified.
st_mtime Same as st_ctime.
st_dev Physical device ID (do not try to interpret this field, but it
does represent the DOS handler).
st_ino inode ID (usually a file block number on the Amiga).
|| NOTE: On the Amiga one normally cannot directly examine a file
|| that is exclusively locked. If this case occurs, stat will
|| attempt to scan the parent directory for the file and if that
|| doesn't work, returns -1.
INPUTS
char *name; name of file to stat
struct stat *sbuf;
address of stat structure that will be filled in
RESULTS
int error; 0 on success, < 0 on error
SEE ALSO
chdir
EXAMPLE
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
main(int ac, char**av)
{
int r;
struct stat stat_buf;
if (ac == 1) {
puts("Expected a test file name");
exit(1);
}
r = stat(av[1], &stat_buf);
if (r < 0)
printf("Can't stat %s\n", av[1]);
else {
printf("File is %d bytes long\n", stat_buf.st_size);
printf("modified %s", ctime(&stat_buf.st_ctime));
}
return(0);
}
dice/stdin,stdout,stderr,EOF dice/stdin,stdout,stderr,EOF
FUNCTION
stdin: standard input channel (file pointer - MACRO)
stdout: standard output channel (file pointer - MACRO)
stderr: standard error channel (file pointer - MACRO)
EOF: special value representing End-Of-File
SYNTAX
#include <stdio.h>
DESCRIPTION
stdin is the name for the program's standard input stream, a "FILE *"
(Pointer to structure FILE). This can be redirected via command line
redirection when the program is run. stdout is a FILE * type that
represents the program's standard output stream. This can also be
redirected via command line redirection when the program is run.
stderr is a FILE * type that represents the program's standard error
stream. Currently stderr is opened by _main and represents the
console device associated with the program regardless of standard
redirections. EOF is special value, -1 in this implementation, that
represents an end of file marker. Functions that return a single
character actually return type int to allow EOF to be distinct from
valid characters. Include the file stdio.h to use these defintions.
These file pointers may be fclose'd or freopen'd at any time. The
stdio macros getchar and putchar and stdio library routines gets and
puts deal with stdin and stdout respectively while other library
routines such as perror output to stderr.
dice/stpchr dice/stpchr
FUNCTION
Search for a character in a string (UNIX)
SYNTAX
#include <string.h>
char *ptr = stpchr(s, c)
const char *s;
int c;
DESCRIPTION
This searches for the character c within the string pointed to by s.
The terminating NULL at the end of s is NOT included in the search.
A pointer to the first occurance of c in s is returned or NULL if c
could not be found. c is converted to a char by stpchr before
beginning the search.
|| NOTE: It is better to use the ANSI standard strchr and strrchr
|| functions.
INPUTS
char *s; pointer to string to search
int c; character to search for
RESULTS
char *ptr; pointer to the first occurance of the character c
in s, or NULL if c could not be found in s.
SEE ALSO
strchr, strrchr
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
main()
{
char *s = "this is a test";
char *ptr;
ptr = stpchr(s, 'i');
assert(ptr == s + 2);
puts(ptr); /* "is is a test" */
return(0);
}
dice/stpcpy dice/stpcpy
FUNCTION
copy a string returning a pointer to the end of the destination
(UNIX)
SYNTAX
#include <string.h>
char *ptr = stpcpy(d, s);
char *d;
char *s;
DESCRIPTION
This function copies the NULL terminated string pointed to by s to
the buffer d. The NULL is copied. A pointer to the NULL character
at the end of the copied string in d is returned.
|| NOTE: stpcpy is non-standard. While a stpcpy/stpcpy combination
|| is more efficient than a strcpy/strcat combination, strcpy and
|| strcat are standard functions and thus are guaranteed to exist in
|| all environments.
INPUTS
char *d; pointer to beginning of destination buffer
char *s; pointer to beginning of source string
RESULTS
char *ptr; pointer to end of data copied to destination
buffer
SEE ALSO
strcpy, strbpl
EXAMPLE
#include <stdio.h>
#include <string.h>
main()
{
char *buf1 = "Micky ";
char *buf2 = "Moose";
char dest[32];
char *ptr;
ptr = stpcpy(dest, buf1);
stpcpy(ptr, buf2);
puts(dest); /* Micky Moose */
return(0);
}
dice/strbpl dice/strbpl
FUNCTION
unpack a string-array buffer into an array of pointers (DICE)
SYNTAX
#include <string.h>
int num = strbpl(av, max, sary)
char **av;
int max;
const char *sary;
DESCRIPTION
strbpl unpacks a string-array into an array of string pointers. The
string array is a series of NULL terminated strings strung together
and terminated by a final NULL. A pointer to each string is placed
in the arary-of-pointers (av) with a final NULL entry assuming the
number of strings does not exceed (max-1).
INPUTS
char **av; pointer to a preallocated array of pointers
int max; the maximum number of entries in the above array
char *sary; pointer to a packed string.
RESULTS
int num; number of pointers loaded into the av array not
including the final NULL. If num == max then the
av array was not large enough to fit all the
strings or the final NULL.
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
main()
{
char *sary = "this\0is\0a\0test\0\0";
char *av[16];
int n;
#define arysize(x) (sizeof(x)/sizeof((x)[0]))
n = strbpl(av, arysize(av), sary);
assert(n == 4); /* n == 4 */
puts(av[0]); /* this */
puts(av[1]); /* is */
puts(av[2]); /* a */
puts(av[3]); /* test */
assert(av[4] == NULL); /* av[4] == NULL */
return(0);
}
dice/strcat dice/strcat
FUNCTION
concactenate a string to an existing string (ANSI)
SYNTAX
#include <string.h>
char *d = strcat(d, s);
char *d;
const char *s;
DESCRIPTION
strcat scans the destination buffer for the NULL terminator and then
appends the source string to the destination buffer (removing the
NULL terminator and placing one at the end after the concactenation).
A pointer to the beginning of the destination buffer is returned.
INPUTS
char *d; pointer to destination buffer which already
contains a string (which could be just a \0).
char *s; pointer to the NULL terminated source string
RESULTS
char *d; same as the first argument, a pointer to the
destination buffer.
SEE ALSO
strncpy, strcpy, strncat
EXAMPLE
#include <stdio.h>
#include <string.h>
main()
{
char dest[80];
char *s1 = "I had an elegant proof also, ";
char *s2 = "but the console window was too narrow...";
strcpy(dest, s1);
puts( strcat(dest, s2) ); /* returns its first arg */
}
dice/strchr dice/strchr
FUNCTION
search for a character in a string (ANSI)
SYNTAX
#include <string.h>
char *ptr = strchr(s, c)
const char *s;
int c;
DESCRIPTION
This searches for the character c within the string pointed to by s.
The terminating NULL at the end of s is included in the search. A
pointer to the first occurance of c in s is returned or NULL if c
could not be found. C is converted to a char by strchr before
beginning the search.
|| NOTE: While strchr(s, 0); may be used to find the end of the
|| string this is slow compared to using the construction: char *ptr
|| = s + strlen(s); /* ptr = end of string s */.
INPUTS
char *s; pointer to the string to search
int c; character to search for.
RESULTS
char *ptr; pointer to the first occurance of character c in
s or NULL if c could not be found in s.
SEE ALSO
strrchr
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
main()
{
char *s = "We feel incredibly agile";
char *ptr;
ptr = strchr(s, 'i');
assert(ptr == s + 2);
puts(ptr); /* "incredibly agile" */
return(0);
}
dice/strcmp dice/strcmp
FUNCTION
compare two strings (ANSI)
SYNTAX
#include <string.h>
int r = strcmp(s1, s2);
const char *s1;
const char *s2;
DESCRIPTION
strcmp compares two strings, returning -1 if s1 < s2, 0 if s1 == s2
, and 1 if s1 > s2.
|| NOTE: strcmp converts the chars in the string to unsigned
|| quantities when comparing them. However, for portability you
|| should not strcmp strings containing negative characters (bit 7
|| set) for anything other than checking the result against 0. Use
|| the memcmp routine instead.
INPUTS
char *s1; pointer to first string
char *s2; pointer to second string
RESULTS
int r; -1, 0, or 1.
SEE ALSO
strncmp, stricmp
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
main()
{
char *s1 = "abca";
char *s2 = "abcd";
char *s3 = "abcx";
char *s4 = "abcdx";
char *s5 = "abc";
char *x2 = "abcd";
int r;
r = strcmp(s2, x2);
/* string s2 same as string x2 */
assert(r == 0);
r = strcmp(s2, s1);
/* string s2 larger than string s1*/
assert(r > 0);
r = strcmp(s2, s3);
assert(r < 0);
r = strcmp(s2, s4);
assert(r < 0);
r = strcmp(s2, s5);
assert(r > 0);
return(0);
}
dice/strcpy dice/strcpy
FUNCTION
copy a string returning a pointer to the beginning of the destination
(ANSI)
SYNTAX
#include <string.h>
char *ptr = strcpy(d, s);
char *d;
char *s;
DESCRIPTION
strcpy copies the NULL terminated string pointed to by s to the
buffer d. The NULL is copied. The first argument is returned (a
pointer to the buffer d).
INPUTS
char *d; pointer to beginning of destination buffer
char *s; pointer to beginning of source string
RESULTS
char *ptr; same as the destination buffer pointer (d).
SEE ALSO
stpcpy
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
/*
* Note that the stpcpy() example accomplishes the same
* thing and is more efficient, but also requires the
* use of a temporary pointer as well as cluttering the
* source and being non-standard.
* strcpy()/strcat() is more portable, though less
* efficient.
*/
main()
{
char *buf1 = "saber";
char *buf2 = "tooth";
char dest[32];
strcpy(dest, buf1);
strcat(dest, buf2);
puts(dest); /* sabertooth */
return(0);
}
dice/strcspn dice/strcspn
FUNCTION
scan a string until a character is found that matches any character
in a second string (ANSI)
SYNTAX
#include <string.h>
int len = strcspn(s, toks)
const char *s;
const char *toks;
DESCRIPTION
With strcspn, the string s is scanned until a character is found that
matches any character in the string toks. The number of characters
skipped is returned. If no character in s matches any character in
toks then the length of the string s is returned.
strcspn is normally used to search for whitespace within a string.
Note that in many cases strpbrk is more useful than strcspn.
INPUTS
char *s; pointer to string to scan
char *toks; pointer to string containing characters to
compare against
RESULTS
int len; # of characters skipped in s before a match was
found.
SEE ALSO
strpbrk, strspn
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
main()
{
int len;
len = strcspn("hello this is a test", " \tabcd");
assert(len == 5); /* stopped at the first space */
len = strcspn("hello this is a test", " abl");
assert(len == 2); /* stopped at the first 'l' */
len = strcspn("hello", "abcd");
assert(len == 5); /* stopped at end of string 1 */
return(0);
}
dice/strdup dice/strdup
FUNCTION
duplicate a string using malloc (DICE)
SYNTAX
#include <string.h>
char *s2 = strdup(s1);
const char *s1;
DESCRIPTION
strdup allocates enough space to hold s1 including the terminating
NULL and then copies s1 into this space, returning a pointer to the
new string. NULL is returned if space could not be allocated due to
low memory conditions. Note free may be used to free the returned
string. The amount allocated is (strlen(s1) + 1).
|| NOTE: This is a non-standard function and may not exist in other C
|| environments.
INPUTS
char *s1; pointer to the string to duplicate
RESULTS
char *s2; pointer to malloc'd space containing a duplicate
of the string s1 or NULL if space could not be
malloc'd.
SEE ALSO
malloc, free, strcpy, strlen
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
/*
* Modifying string constants (quoted strings) may
* not be entirely portable. Normally one does not
* use strdup() to accomplish the following function
* but instead declares a char array statically
* initialized with the string, such as:
* char FuBar[] = { "This is a test" };
* Which can be modified in a portable fashion without
* having to duplicate the string.
*/
main()
{
char *s1 = "this is a test";
char *s2;
s2 = strdup(s1);
s2[0] = 'x';
puts(s2); /* this is a test */
free(s2);
s2 = strdup(s1);
s2[1] = '0';
puts(s2); /* this is a test */
free(s2);
return(0);
}
dice/strerror dice/strerror
FUNCTION
return error string associated with error code (ANSI)
SYNTAX
#include <string.h>
const char *str = strerror(error); int error;
DESCRIPTION
strerror returns a read-only string associated with the specified
error, usually taken from errno after some c.lib call fails. An
unknown error will result in the string "unknown error."
INPUTS
int error; error code
RESULTS
char *str; error string
SEE ALSO
perror
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
main()
{
FILE *fi;
fi = fopen("ThisFileDoesNotExist", "r");
assert(fi == NULL);
puts(strerror(errno));
return(0);
}
dice/strftime dice/strftime
FUNCTION
convert broken down time into a string according to a format (ANSI)
SYNTAX
#include <time.h>
size_t len = strftime(buf, max, fmt, tm)
char *buf; size_t max;
const char *fmt;
const struct tm *tm;
DESCRIPTION
strftime formats a broken down time into a buffer according to a
format string fmt. The fmt string looks like a the format for a
printf except with different control definitions:
%% A literal '%' character.
%a The locale's abbreviated name for the day of week.
%A The locale's full name for the day of week.
%b The locale's abbr. name for the month.
%B The locale's full name for the month.
%c The locale's default representation for the date & time (ctime).
%d The day of the month 01-31.
%H The hour 00-23 (24 hour time).
%I The hour 01-12 (12 hour time).
%j The day in the year 001-366.
%m The month 01-12.
%M The minute 00-59.
%p Indication of morning or afternoon. In the US: "AM" or "PM".
%S The second 00-59.
%U The week of the year 00-53, Sunday is the first day in a week.
%w The day of the week 0-6, Sunday=0 (standard).
%W The day of the week 0-6, monday=0.
%x The locale's default representation for the date only.
%X The locale's default representation for the time only.
%y The year mod 100 (00-99).
%Y The full year (e.g. 1990).
%Z The name of the locale's time zone, nothing if unknown.
## WARNING: There must be at least max + 1 bytes in buf or you
## might unexpectedly overwrite memory.
INPUTS
char *buf; buffer to write formatted string into
size_t max; maximum size of buffer - 1
char *fmt; format string
struct tm *tm; broken down time
RESULTS
size_t len; length of formatted string in buffer or 0 if the
maximum was exceeded.
SEE ALSO
time, localtime, asctime, ctime, clock
EXAMPLE
#include <stdio.h>
#include <time.h>
main()
{
time_t t = time(NULL);
struct tm *tp = localtime(&t);
char buf[256];
strftime(buf, sizeof(buf) - 1,
"Now is %A %d %B %Y %X", tp);
puts(buf);
return(0);
}
dice/stricmp dice/stricmp
FUNCTION
compare two strings, case insensitive (UNIX)
SYNTAX
#include <string.h>
int r = stricmp(s1, s2);
const char *s1;
const char *s2;
DESCRIPTION
stricmp compares two strings, returning: -1 if s1 < s2, 0 if s1 ==
s2, or 1 if s1 > s2. differs from strcmp in that case is ignored for
alphabetic characters, i.e. a == A.
|| NOTE: NOTE= stricmp converts the chars in the string to unsigned
|| quantities when comparing them. However, for portability you
|| should not stricmp strings containing negative characters (bit 7
|| set) for anything other than checking the result against 0. Use
|| the memcmp routine instead.
INPUTS
char *s1; pointer to first string
char *s2; pointer to second string
RESULTS
int r; -1, 0, or 1.
SEE ALSO
strcmp, strncmp
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
main()
{
char *s1 = "abCa";
char *s2 = "aBcD";
char *s3 = "aBCX";
char *s4 = "ABCdx";
char *s5 = "Abc";
char *x2 = "ABCD";
int r;
r = stricmp(s2, x2); /* string s2 same as x2 */
assert(r == 0);
r = stricmp(s2, s1); /* string s2 larger than s1 */
assert(r > 0);
r = stricmp(s2, s3);
assert(r < 0);
r = stricmp(s2, s4);
assert(r < 0);
r = stricmp(s2, s5);
assert(r > 0);
return(0);
}
dice/strins dice/strins
FUNCTION
insert one string within another (DICE)
SYNTAX
#include <string.h>
void strins(d, s);
char *d;
const char *s;
DESCRIPTION
strins inserts string s into d by shifting the string in d over
strlen(s) spaces and then copying s into the newly made hold (except
for the NULL, of course). This result is s inserted into d.
|| NOTE: There must be enough room in d to insert s; if d is an array
|| of 32 chars and contains a string of 8 chars you can insert
|| another string of, say, 10 chars, but not of 30 chars. strins is
|| not an ANSI standard function.
INPUTS
char *d; destination to insert in front of
char *s; source string to insert
SEE ALSO
strcpy, strcat, strlen
EXAMPLE
#include <stdio.h>
#include <string.h>
main()
{
char buf[32];
strcpy(buf, "This is a test");
strins(buf + 5, "<gak!> ");
puts(buf);
/* This <gak!> is a test */
return(0);
}
dice/strlen dice/strlen
FUNCTION
returns length of a string (ANSI)
SYNTAX
#include <string.h>
int len = strlen(s);
const char *s;
DESCRIPTION
When this function is used, the length of the requested string is
returned. The string is scanned until a NULL terminator is found and
the number of characters (not including the NULL) is returned.
:: Beginner's Note: The length returned by strlen does not include
:: the NULL. It is common error to forget this fact and reserve one
:: too few bytes of storage!
INPUTS
char *s; string to obtain length of
RESULTS
int len; length of string
SEE ALSO
strcpy, strcat
EXAMPLE
#include <stdio.h>
#include <string.h>
main(int ac, char **av)
{
if( ac 1 ) {
printf("%s is %d byte(s) long\n",
av[1], strlen( av[1] ) );
} else
printf("Gimme, gimme, gimme!!\n");
}
dice/strncat dice/strncat
FUNCTION
concactenate a string to an existing string up to a maximum number of
characters (ANSI)
SYNTAX
#include <string.h>
char *d = strncat(d, s, n);
char *d;
const char *s;
int n;
DESCRIPTION
strncat scans the destination buffer for the NULL terminator and then
appends the source string to the destination buffer (removing the
NULL terminator and placing one at the end after the concactenation).
However, only up to n characters is concactenated including the NULL.
If the source string is exactly n characters long no NULL will be
appended. If the source string is longer than n characters then only
the first n characters of the source string will be appended (and no
NULL will be). A pointer to the beginning of the destination buffer
is returned.
INPUTS
char *d; pointer to destination buffer which already
contains a string (which could be just a \0).
char *s; pointer to the NULL terminated source string
int n; maximum number of characters to concactenate
RESULTS
char *d; same as the first argument, a pointer to the
destination buffer.
SEE ALSO
strncpy, strcpy, strcat
EXAMPLE
#include <stdio.h>
#include <string.h>
main()
{
char d[32]; char *p;
char *s1 = "grid"; char *s2 = "lock";
strcpy( d, s1 );
p = strncat( d, s2, 10 );
puts( d ); /* gridlock */
strcpy( d,I s1 );
p = strncat( d, s2, 3 );
puts( d ); /* gridloc */
return(0);
}
dice/strncmp dice/strncmp
FUNCTION
compare two strings up to a maximum number of characters (ANSI)
SYNTAX
#include <string.h>
int r = strncmp(s1, s2, n);
const char *s1;
const char *s2;
int n;
DESCRIPTION
strncmp compares two strings, returning: -1 if s1 < s2, 0 if s1 ==
s2, or 1 if s1 > s2. strncmp works like strcmp but only up to n
characters will be compared. If all characters compare when n is
reached 0 is returned indicating that the strings matched. Fewer
characters might be compared if either string terminates (w/ a NULL)
before the maximum is reached or a compare fails (scan is stopped and
-1 or 1 is returned immediately).
|| NOTE: strncmp converts the chars in the string to unsigned
|| quantities when comparing them. However, for portability you
|| should not strncmp strings containing negative characters (bit 7
|| set) for anything other than checking the result against 0. Use
|| the memcmp routine instead.
INPUTS
char *s1; pointer to first string
char * s2; pointer to second string
int n; maximum number of characters to compare
RESULTS
int r; -1, 0, or 1.
SEE ALSO
stricmp
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
main()
{
char *s1 = "abcaq";
char *s2 = "abcdr";
char *s3 = "abcxs";
char *s4 = "abcdxx";
char *s5 = "abc";
char *x2 = "abcdt";
int r; r = strncmp(s2, x2, 4);
assert(r == 0);
r = strncmp(s2, s1, 4);
assert(r > 0);
r = strncmp(s2, s3, 4);
assert(r < 0);
r = strncmp(s2, s4, 8);
assert(r < 0);
r = strncmp(s2, s5, 4);
assert(r > 0);
return(0);
}
dice/strncpy dice/strncpy
FUNCTION
copy a string returning a pointer to the beginning of the destination
until NULL or the specified number of characters is reached (ANSI)
SYNTAX
#include <string.h>
char *ptr = strncpy(d, s, n);
char *d;
const char *s;
int n;
DESCRIPTION
strncpy copies the NULL terminated string pointed to by s to the
buffer d. The NULL is normally copied. The first argument is
returned (a pointer to the buffer d). The copy will also be
terminated if the specified maximum is reached, in which case the
NULL is NOT copied (which makes the function useless - but hey, it
does make it standard).
INPUTS
char *d; pointer to beginning of destination buffer
char *s; pointer to beginning of source string
int len; maximum number of characters to copy
RESULTS
char *ptr; same as the destination buffer pointer (d).
SEE ALSO
stpcpy, strcpy
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
main()
{
char *buf1 = "hello";
char *buf2 = "123";
char dest[32];
strncpy(dest, buf1, 8);
strcat(dest, buf2);
puts(dest); /* hello123 */
dest[2] = 23;
strncpy(dest, buf1, 2);
assert(dest[2] == 23); /* copy just two */
dest[2] = 0; /* we have to add the NULL */
puts(dest); /* he */
strcat(dest, buf2); /* he123 */
puts(dest);
return(0);
}
dice/strnicmp dice/strnicmp
FUNCTION
compare two strings up to a maximum number of characters, case
insensitive (UNIX)
SYNTAX
#include <string.h>
int r = strnicmp(s1, s2, n);
const char *s1;
const char *s2;
int n;
DESCRIPTION
strnicmp compares two strings, returning: -1, s1 < s2; 0, s1 ==
s2; 1, s1 > s2. strnicmp differs from strcmp in that case is
ignored for alphabetic characters (i.e., a == A) and only up to n
characters are compared. Refer to stricmp and strncmp for other
examples.
|| NOTE: strnicmp converts the chars in the string to unsigned
|| quantities when comparing them. However, for portability you
|| should not strnicmp strings containing negative characters (bit 7
|| set) for anything other than checking the result against 0. Use
|| the memcmp routine instead.
INPUTS
char *s1; pointer to first string
char *s2; pointer to second string
int n; maximum # of characters to compare
RESULTS
int r; -1, 0, or 1.
SEE ALSO
strcmp, strncmp, stricmp
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
main()
{
char *s1 = "aBcAQ";
char *s2 = "abCDR";
char *s3 = "ABcXs";
char *s4 = "aBCDxX";
char *s5 = "aBC";
char *x2 = "AbCDt";
int r;
r = strnicmp(s2, x2, 4);
assert(r == 0);
r = strnicmp(s2, s1, 4);
assert(r > 0);
r = strnicmp(s2, s3, 4);
assert(r < 0);
r = strnicmp(s2, s4, 8);
assert(r < 0);
r = strnicmp(s2, s5, 4);
assert(r > 0);
return(0);
}
dice/strpbrk dice/strpbrk
FUNCTION
search for specific characters in a string (ANSI)
SYNTAX
#include <string.h>
char *ptr = strpbrk(s, toks)
const char *s;
char *toks;
DESCRIPTION
strpbrk searches the string s for any character in the string toks.
For example, when searching for whitespace in s, toks would contain
the space and tab character. If no character in s matches any
character in toks then NULL is returned.
INPUTS
char *s; pointer to string to scan
char *toks; pointer to string containing tokens to scan for
RESULTS
char *ptr; pointer to point in s where the character matches
any character in toks, or NULL if s was
exhausted.
SEE ALSO
strtok
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
main()
{
char *s = "This \tis a test";
char *ptr;
ptr = strpbrk(s, " \t");
assert(ptr == s + 4);
ptr = strpbrk(ptr + 1, " \t");
assert(ptr == s + 5);
ptr = strpbrk(ptr + 1, " \t");
assert(ptr == s + 6);
ptr = strpbrk(ptr + 1, " \t");
assert(ptr == s + 9);
ptr = strpbrk(ptr + 1, "xyz"); /* doesn't find 'm */
assert(ptr == NULL);
return(0);
}
dice/strrchr dice/strrchr
FUNCTION
search for a character in a string, scan backwards (ANSI)
SYNTAX
#include <string.h>
char *ptr = strrchr(s, c)
const char *s;
int c;
DESCRIPTION
strrchr searches for the character c within the string pointed to by
s. The terminating NULL at the end of s is included in the search.
The string is searched backwards. A pointer to the last occurrance of
c in s is returned or NULL if c could not be found. C is converted
to an 8 bit quantity by strrchr.
|| NOTE: The ANSI spec does not say anything about including the NULL
|| character in the search for strrchr and some implementation may
|| thus not implement this properly.
INPUTS
char *s; pointer to the string to search
int c; character to search for
RESULTS
char *ptr; pointer to the last occurance of character c in s
or NULL if c could not be found in s.
SEE ALSO
strchr
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
main()
{
char *s = "this is a test";
char *ptr;
ptr = strrchr(s, 'i');
assert(ptr == s + 5);
puts(ptr); /* "is a test" */
ptr = strrchr(s, 'x');
assert(ptr == NULL);
return(0);
}
dice/strspn dice/strspn
FUNCTION
scan a string until a character is found that does not match some
character in a second string (ANSI)
SYNTAX
#include <string.h>
int len = strspn(s, toks)
const char *s;
const char *toks;
DESCRIPTION
The string s is scanned until a character is found that does not
match any character in the string toks. The number of characters
skipped is returned. If every character in s matches some character
in toks then the length of the string s is returned.
strspn is normally used to skip whitespace within a string.
INPUTS
char *s; pointer to string to scan
char *toks; pointer to string containing characters to
compare against
RESULTS
int len; # of characters skipped in s before a match could
not be found
SEE ALSO
strpbrk, strcspn
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
main()
{
int len;
len = strspn(" \t \t\t abcde test", " \t ");
assert(len == 7); /* stopped at the 'a' */
len = strspn("abcd efg", " ");
assert(len == 0); /* stopped at the 'a' */
len = strspn(" \t\t ", " \t");
assert(len == 6); /* all match, len=strlen(str); */
return(0);
}
dice/strstr dice/strstr
FUNCTION
find sub-string within another string (ANSI)
SYNTAX
#include <string.h>
char *ptr = strstr(s, sub);
const char *s;
const char *sub;
DESCRIPTION
The string s is scanned until the sub-string sub matches the string
beginning at the current scan point, and a pointer to the sub-string
within s is returned. If the sub-string could not be found NULL is
returned.
INPUTS
char *s; pointer to string to scan
char *toks; pointer to string containing characters to
compare against
RESULTS
char *ptr; point in s where sub string was found or NULL if
sub string could not be found.
SEE ALSO
strpbrk, strcspn
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
main()
{
char *s = "abcdefghijklmnopqrstuvwxyz";
char *ptr;
ptr = strstr(s, "klm");
assert(ptr == s + 10);
puts(ptr); /* klmnopqrstuvwxyz */
return(0);
}
dice/strtod dice/strtod
FUNCTION
convert string to fp double (ANSI)
LIBRARY
m.lib
SYNTAX
#include <string.h>
double d = strtod(s, &tp);
const char *s;
char *tp;
DESCRIPTION
strtod converts a string to a floating point double. Initial
whitespace is skipped. The format of the fp number in the string is
then:
{+/-/<nothing>}ddddd[.ddddd][E{+/-/<nothing>}dddd]
Example fp strings: " +1.234E-3", "-1234", "6.5676E4", "214.2345"
INPUTS
char *s; pointer to string containing fp number
char **tp; pointer to pointer, the pointer is modified to
point to the end of the scanned fp number.
RESULTS
double d; resulting double
EXAMPLE
/*
* compile -lm to include math library
*/
#include <stdio.h>
#include <string.h>
main()
{
double d;
char *tp;
d = strtod("1.2134 3.45E2", &tp);
printf("1.2134 = %lf\n", d); /* 1.213400 */
d = strtod(tp, &tp);
printf("3.45E2 = %lf\n", d); /* 345.000000 */
return(0);
}
dice/strtok dice/strtok
FUNCTION
break up a string into arguments (ANSI)
SYNTAX
#include <string.h>
char *arg = strtok(s, toks)
char *s;
const char *toks;
DESCRIPTION
strtok breaks up a string into arguments. It determines the break
point from the toks string which contains a set of whitespace
characters (usually \t to mean space and tab). The first call to
strtok should specify the string s and toks. Initial whitespace is
skipped and the string is then scanned until the end of the first
argument is found. The string is then modified: a NULL is placed at
the end of the first argument and a pointer to the beginning of the
first argument is returned.
Further calls to strtok should pass a NULL for the string s, which
tells strtok to continue scanning the original string (whose pointer
was stored in a static char * within strtok). strtok returns
arguments until the string is exhausted, in which case it returns
NULL. The initial call to strtok can return NULL if the passed
string s contains nothing but whitespace (as specified by toks). You
can change the toks string at any time (i.e. pass a different toks
string to strtok).
## WARNING: strtok modifies the source string and returns pointers
## into it.
INPUTS
char *s; pointer to string to parse
char *toks; pointer to string containing whitespace
characters (argument delimiters)
RESULTS
char *arg; pointer into s to next argument that is NULL
terminated (s is modified).
SEE ALSO
strspn, strcspn
EXAMPLE
#include <stdio.h>
#include <string.h>
main()
{
char buf[32];
char *arg;
const char *ws = " \t";
/*
* 'This' 'is' 'a' 'test!'
*/
strcpy(buf, " This is \t \t a test!");
for (arg = strtok(buf, ws);
arg; arg = strtok(NULL, ws))
{
printf("arg = '%s'\n", arg);
}
return(0);
}
dice/strtol,strtoul dice/strtol,strtoul
FUNCTION
convert string to integer (ANSI)
SYNTAX
#include <string.h>
long v = strtol(str, &tail, base);
unsigned long v = strtoul(str, &tail, base);
const char *str;
char *tail;
int base;
DESCRIPTION
strtol converts a string into an integer using the specified base
0-36. If a non-zero base is specified conversion is done using that
base (hex numbers may still be preceeded by '0x' or '0X'). If 0 is
specified for the base then the base is determined from the first one
or two characters of the number portion of the string:
0 octal
1-9 decimal
0x hex (0x or 0X)
For bases larger than 10, alphabetic characters are used to represent
digits. Either lower case or upper case letters may be used. strtol
stores a pointer to the remainder of the string after the conversion.
strtol ignores any whitespace at the beginning of the string and also
handles an optional negative sign (which may precede the numerical
portion of the string).
If successful strtol returns the converted value as a long, 0 if it
was unable to convert anything, and an undefined result if the
converted value was out of range.
|| NOTE: strtol supersedes atoi and atol.
INPUTS
char *str; pointer to string to convert
char **tail; *tail modified to point to just after last
character converted
int base; base of conversion or 0 for autoselect
RESULTS
long v; converted result, an integer, or 0 if no
conversion could be done.
SEE ALSO
atoi, atol, strtod
EXAMPLE
#include <stdio.h>
#include <string.h>
main(int ac, char**av)
{
long v;
char *tail;
if (ac != 3)
{
puts("testprg <string> <base>");
puts("testprg 0123abc 0");
puts("testprg 0x1000 0");
puts("testprg 0123abc 16");
exit(1);
}
v = strtol(av[1], &tail, atoi(av[2]));
printf("v = %d, tail = %s\n", v, tail);
return(0);
}
dice/system dice/system
FUNCTION
call system shell with a command line (ANSI)
SYNTAX
#include <stdio.h>
#include <stdlib.h>
int r = system(buf);
const char *buf;
DESCRIPTION
system calls the system shell with the specified command line,
returning the exit code of the command or -1 if it was unable to run
the command.
|| NOTE: FOR PROGRAMS COMPILED UNDER 1.3, even if run in 2.0
|| enviroment, the system call will not return the exit code from the
|| command, but return -1 if could not be run, 0 if it could.
|| NOTE: FOR PROGRAMS COMPILED UNDER 2.0, system will use the 2.0
|| calls and return a proper exit code when running under 2.0, and
|| will use execute if running under 1.3.
INPUTS
char *buf; command line to run, like a normal AmigaDOS CLI
command line.
RESULTS
int r; return code
EXAMPLE
main()
{
int r;
r = system("c:type s:startup-sequence");
printf("System returns %d\n", r);
}
dice/tan,ftan dice/tan,ftan
FUNCTION
tan: return tan of a double quantity (ANSI)
ftan: return tan of a float quantity (ANSI)
LIBRARY
m.lib
SYNTAX
#include <math.h>
double a = tan(b); double b;
float c = ftan(d); float d;
DESCRIPTION
tan returns the tangent of a double quantity; ftan returns the
tangent of a floating point quantity.
INPUTS
double b; double floating point value
float d; float floating point value
RESULTS
double a; double floating point value
float c; float floating point value
SEE ALSO
acos, asin, atan, cos, exp, fabs, log, log10, pow, sin, sqrt, tan,
facos, fasin
EXAMPLE
/*
* compile with the math library -lm
*/
#include <math.h>
#include <stdio.h>
main()
{
{
double a = tan(0.25);
printf("tan 0.25 = %lf\n", a); /* 0.2553 */
}
{ /* less accuracy */
float a = ftan(0.25);
printf("tan 0.25 = %lf\n", (double)a);
}
return(0);
}
dice/time dice/time
FUNCTION
get current time (ANSI)
SYNTAX
#include <time.h>
time_t t = time(NULL);
or
time(&t);
time_t t;
DESCRIPTION
time returns the current time as a time_t and also copies it into a
time_t if the address of said is passed as an argument. You may pass
NULL as an argument in which case the time is only returned.
The time is returned as seconds since some base date, time_t is
normally an unsigned long.
INPUTS
time_t *t; pointer to a time_t or NULL
RESULTS
time_t t; a time_t
SEE ALSO
time, localtime, asctime, strftime, ctime, clock
EXAMPLE
#include <stdio.h>
#include <time.h>
main()
{
time_t t = time(NULL);
printf("t = %u\n", t);
return(0);
}
dice/tmpfile dice/tmpfile
FUNCTION
create a temporary file (ANSI)
SYNTAX
#include <stdio.h>
FILE *fp = tmpfile(void);
DESCRIPTION
tmpfile creates a temporary file and returns a file pointer. The
name of the file is not accessible. The file pointer is available or
reading, writing, and seeking (as in rewind, fseek). The file is
initially empty. This call may be used to create a temporary file
that will automatically be removed when you fclose it. tmpfile
returns a FILE pointer or NULL if it was unable to create the file.
INPUTS
none
RESULTS
FILE *fp; opened temporary file
SEE ALSO
tmpnam, fopen, fclose
EXAMPLE
#include <stdio.h>
#include <assert.h>
main()
{
FILE *fp = tmpfile();
char buf[256];
assert(fp);
fputs("This is a test of\n"
"a temporary file\n"
"fubar bletch\n", fp);
rewind(fp);
while (fgets(buf, sizeof(buf), fp))
{
fputs(buf, stdout);
}
fclose(fp); /* close and delete the file */
return(0);
}
dice/tmpnam dice/tmpnam
FUNCTION
create a unique, temporary file name (ANSI)
SYNTAX
#include <stdio.h>
char *filename = tmpnam(buf);
char *buf;
DESCRIPTION
tmpnam creates a unique temporary file name meant never to be seen by
the user. The filename tmpnam creates will be no more than L_tmpnam
bytes long (L_tmpnam is a macro in <stdio.h>), including the NULL so
you can simply declare a buffer: char buf[L_tmpnam];.
tmpnam returns the buffer into which it created the temporary file
name. If you specify a non-NULL buffer it returns its first
argument. If you pass NULL to tmpnam then tmpnam will use its down
internal static buffer (overwritting any previous name that was
stored in said buffer) and return a pointer to that.
INPUTS
char *buf; optional buffer of at least L_tmpnam bytes to
hold the temporary file name or NULL to have
tmpnam() use its own internal buffer.
RESULTS
char *ptr; pointer to buffer (buf if buf != NULL)
SEE ALSO
tmpfile
EXAMPLE
#include <stdio.h>
#include <assert.h>
main()
{
char buf[L_tmpnam]; char *ptr;
ptr = tmpnam(NULL); puts(ptr);
assert(tmpnam(buf) == buf);
/* returns argument */
puts(buf); /* haven't overwritten it yet */
printf("%s (same as first)\n", ptr);
assert(tmpnam(NULL) == ptr);
/* that will overwrite it! */
puts(ptr);
return(0);
}
dice/tolower,toupper dice/tolower,toupper
FUNCTION
convert a character into lower or upper case (ANSI)
SYNTAX
#include <ctype.h>
int lc = tolower(c);
int uc = toupper(c);
int c;
|| NOTE: These are MACROS if you #include <ctype.h>, subroutine calls
|| if you do not.
DESCRIPTION
toupper converts a character from lower to upper case, while tolower
does the reverse. Characters that are not of type upper or lower
case (see isupper and islower) are left unchanged.
|| NOTE: Characters in the -1 to 255 range are valid inputs.
|| Characters less than -1 or larger than 255 are illegal and the
|| results will be random. If you are passing a CHAR, you must cast
|| it to an UNSIGNED CHAR first. EOF is a valid input an always
|| returns false (zero).
INPUTS
int c; character to be converted
RESULTS
int lc, uc; converted character
SEE ALSO
isalnum, isalpha, iscntrl, isdigit, isgraph, islower, isprint,
ispunct, isspace, isupper, isxdigit
EXAMPLE
#include <stdio.h>
#include <ctype.h>
main()
{
int c;
/* Print all 256 characters, showing conversions */
for( c=0; c<256; c++) {
if( (c & 31) == 0 ) /* 32 per line */
printf("\n%02x: ", c);
if( isprint( c ) ) /* if printable ... */
printf("%c", tolower( c ) );
else
printf("%c", 127); /* if not-printable */
}
printf("\n");
return( 0 );
}
dice/ungetc dice/ungetc
FUNCTION
push a character back onto a file pointer's input stream (ANSI)
SYNTAX
#include <stdio.h>
int r = ungetc(c, fp);
int c;
FILE *fp;
DESCRIPTION
ungetc pushes the specified character back onto the input stream, as
if it had not been read. Only ONE character may be pushed back onto
an input stream at a time. If all went well, the return value r is
equal to c. Else EOF is returned if too many characters were pushed
back. Some implementations of C allow multiple characters to be
pushed back. The majority, including DICE, allows only one.
ungetc is useful when, in scanning an input stream, you overshoot the
'last' character you wanted a particular routine to retrieve. This
routine can push the character back onto the input stream with ungetc
so another routine's getc (getchar, fread, fgetc, etc...) will get
that character back.
INPUTS
int c; character to push back onto input stream
FILE *fp; file pointer stream to push character on to.
RESULTS
int r; pushed character (c) if no error, EOF if error
SEE ALSO
getc, getchar, fread, fgetc
EXAMPLE
#include <stdio.h>
#include <ctype.h>
main()
{
void scan_number();
void scan_alpha();
puts("Enter nnnaaannn where n=digit a=alpha");
puts("Example: 1234abcd99");
printf("? ");
fflush(stdout);
scan_number(); puts("--");
scan_alpha(); puts("--");
scan_number(); return(0);
}
static void scan_number()
{
short c;
for (c = getchar(); c >= '0' && c <= '9';
c = getchar())
{
printf("digit: %c\n", c);
}
if (c != EOF)
ungetc(c, stdin);
}
static void scan_alpha()
{
short c;
for (c = getchar();
tolower(c) >= 'a' && tolower(c) <= 'z';
c =getchar())
{
printf("alpha: %c\n", c);
}
if (c != EOF) ungetc(c, stdin);
}
dice/unlink dice/unlink
FUNCTION
delete a file (UNIX)
SYNTAX
#include <stdio.h>
int r = unlink(filename);
char *filename;
DESCRIPTION
unlink deletes a file, equivalent to remove. This call deletes a file
from the filesystem. unlink exists for UNIX compatibility only. Use
rmdir to delete a directory if you wish to maintain portability.
INPUTS
char *filename; name of file to delete
RESULTS
int r; 0 if successful, non-zero if error
SEE ALSO
close, creat, fcntl, fdtofh, ioctl, isatty, lseek, mkdir, open, read,
rmdir, unlink, write
EXAMPLE
main()
{
int r;
r = unlink("T:xx");
if (r == 0)
puts("Deleted T:xx");
else
puts("Unable to delete t:xx or it does not exist");
return(0);
}
dice/wbmain dice/wbmain
FUNCTION
main program entry when run from Workbench (DICE)
SYNTAX
#include <startup.h>
int wbmain(struct WBStartup *wbs)
{
/* your main code goes here */
return(exitcode);
}
DESCRIPTION
The wbmain routine is the entry point called after normal
initialization of c.lib and the program enviroment is done by the
startup module (c.o) and _main() routine (in c.lib). wbmain is called
when the program is run from the workbench, main is called when the
program is run from the CLI. The exit code is ignored. The standard
workbench startup message is passed to wbmain, you can process or
ignore this message as you like but should NOT ReplyMsg it. We
repeat, do not ReplyMsg it. When you return from wbmain or exit out
of the program the exit code will automatically deal with the
message.
SEE ALSO
main
EXAMPLE
/*
* If run from the workbench this program will create a
* file T:XX instead of printing something on the
* console (since there is no console in that case).
*/
#include <stdio.h>
int main(int ac, char**av)
{
puts("This was run from a CLI");
return(0);
}
int wbmain(msg)
void *msg; /* cheat to make the example less complex */
{
FILE *fi = fopen("T:xx", "w");
fprintf(fi, "This was run from the WORKBENCH\n");
fclose(fi);
}
dice/write dice/write
FUNCTION
write data to a file (UNIX)
SYNTAX
#include <fcntl.h>
int r = write(fd, buf, bytes);
int fd;
void *buf;
int bytes;
DESCRIPTION
write writes data to a file, starting at the current seek position.
It extends the file if necessary, or else writes over existing data.
With normal files, write will always return the number of bytes
requested and fewer only if an error occurs. With devices write may
or may not return the number of bytes requested depending on the
device, though usually it does.
|| NOTE: Refer to the file_descriptor manual page for general
|| information. Unlike file pointers and file handles, the file
|| descriptor is checked for validity and will simply return an error
|| if illegal.
INPUTS
int fd; file descriptor to write to void
*buf; pointer to buffer to write data from
int len; number of bytes to write
RESULTS
int r; number of bytes actually written, usually an
error if r !=len.
SEE ALSO
close, creat, fcntl, fdtofh, ioctl, isatty, lseek, mkdir, open, read,
rmdir, unlink
EXAMPLE
See open for an example
dice/x.o dice/x.o
FUNCTION
autoinit terminating tags (DICE)
LIBRARY
x.o
DESCRIPTION
The X.O module is the normally the last object module specified when
linking. DICE has a very unique and elegant system of creating
automatic initialization and exit code. The X.O module terminates
these special sections.
Autoinit/exit sections work as follows: any object module may define
a specially named section which will be linked, in sequence, with
other module's sections of the same name. These sections contain
only code and no RTS. The terminating module X.O adds a single RTS
to each section, allowing the base of the section to be called by the
startup/exit module (C.O). Execution propigates through all
autoinit/exit routines before hitting the RTS placed in the section
by X.O. DICE uses autoinit/exit sections to handle the following
things:
1) Code to initialize initialized data containing references to other
initialized data (i.e. int a, *b = &a;) when the code must be
made residentable. This precludes the need for the startup code
to handle Data-Data 32-bit relocations for resident code.
2) Code to open libraries whos base variables are referenced but
never declared. _DOSBase and the various floating point libraries
are automatically opened in this way whenever library calls to
them are made. This precludes the need for DICE to have massive,
complex, and many times unncessary code in c.lib to handle these
situations.
3) Code to close libraries that were openned by (2) on exit.
4) Entry points for the special __autoinit keyword.
SEE ALSO
c.o
EXAMPLE
dlink dlib:c.o myprog.o dlib:x.o -o myprog -v